Imported Upstream version 63.3.0 upstream/63.3.0
authorJinWang An <jinwang.an@samsung.com>
Mon, 27 Mar 2023 08:02:52 +0000 (17:02 +0900)
committerJinWang An <jinwang.an@samsung.com>
Mon, 27 Mar 2023 08:02:52 +0000 (17:02 +0900)
103 files changed:
.bumpversion.cfg
.github/workflows/main.yml
CHANGES.rst
changelog.d/3475.change.rst [new file with mode: 0644]
docs/build_meta.rst
docs/deprecated/commands.rst
docs/setuptools.rst
docs/userguide/quickstart.rst
pyproject.toml
setup.cfg
setuptools/_distutils/_msvccompiler.py
setuptools/_distutils/archive_util.py
setuptools/_distutils/bcppcompiler.py
setuptools/_distutils/ccompiler.py
setuptools/_distutils/cmd.py
setuptools/_distutils/command/__init__.py
setuptools/_distutils/command/_framework_compat.py
setuptools/_distutils/command/bdist.py
setuptools/_distutils/command/bdist_dumb.py
setuptools/_distutils/command/bdist_msi.py
setuptools/_distutils/command/bdist_rpm.py
setuptools/_distutils/command/bdist_wininst.py
setuptools/_distutils/command/build.py
setuptools/_distutils/command/build_clib.py
setuptools/_distutils/command/build_ext.py
setuptools/_distutils/command/build_py.py
setuptools/_distutils/command/build_scripts.py
setuptools/_distutils/command/check.py
setuptools/_distutils/command/config.py
setuptools/_distutils/command/install.py
setuptools/_distutils/command/install_egg_info.py
setuptools/_distutils/command/register.py
setuptools/_distutils/command/sdist.py
setuptools/_distutils/command/upload.py
setuptools/_distutils/config.py
setuptools/_distutils/core.py
setuptools/_distutils/cygwinccompiler.py
setuptools/_distutils/dep_util.py
setuptools/_distutils/dir_util.py
setuptools/_distutils/dist.py
setuptools/_distutils/extension.py
setuptools/_distutils/fancy_getopt.py
setuptools/_distutils/file_util.py
setuptools/_distutils/filelist.py
setuptools/_distutils/msvc9compiler.py
setuptools/_distutils/msvccompiler.py
setuptools/_distutils/spawn.py
setuptools/_distutils/sysconfig.py
setuptools/_distutils/tests/__init__.py
setuptools/_distutils/tests/py38compat.py
setuptools/_distutils/tests/support.py
setuptools/_distutils/tests/test_archive_util.py
setuptools/_distutils/tests/test_bdist.py
setuptools/_distutils/tests/test_bdist_dumb.py
setuptools/_distutils/tests/test_bdist_msi.py
setuptools/_distutils/tests/test_bdist_rpm.py
setuptools/_distutils/tests/test_bdist_wininst.py
setuptools/_distutils/tests/test_build.py
setuptools/_distutils/tests/test_build_clib.py
setuptools/_distutils/tests/test_build_ext.py
setuptools/_distutils/tests/test_build_py.py
setuptools/_distutils/tests/test_build_scripts.py
setuptools/_distutils/tests/test_check.py
setuptools/_distutils/tests/test_clean.py
setuptools/_distutils/tests/test_cmd.py
setuptools/_distutils/tests/test_config.py
setuptools/_distutils/tests/test_config_cmd.py
setuptools/_distutils/tests/test_core.py
setuptools/_distutils/tests/test_cygwinccompiler.py
setuptools/_distutils/tests/test_dep_util.py
setuptools/_distutils/tests/test_dir_util.py
setuptools/_distutils/tests/test_dist.py
setuptools/_distutils/tests/test_extension.py
setuptools/_distutils/tests/test_file_util.py
setuptools/_distutils/tests/test_filelist.py
setuptools/_distutils/tests/test_install.py
setuptools/_distutils/tests/test_install_data.py
setuptools/_distutils/tests/test_install_headers.py
setuptools/_distutils/tests/test_install_lib.py
setuptools/_distutils/tests/test_install_scripts.py
setuptools/_distutils/tests/test_log.py
setuptools/_distutils/tests/test_msvc9compiler.py
setuptools/_distutils/tests/test_msvccompiler.py
setuptools/_distutils/tests/test_register.py
setuptools/_distutils/tests/test_sdist.py
setuptools/_distutils/tests/test_spawn.py
setuptools/_distutils/tests/test_sysconfig.py
setuptools/_distutils/tests/test_text_file.py
setuptools/_distutils/tests/test_unixccompiler.py
setuptools/_distutils/tests/test_upload.py
setuptools/_distutils/tests/test_util.py
setuptools/_distutils/tests/test_version.py
setuptools/_distutils/tests/test_versionpredicate.py
setuptools/_distutils/text_file.py
setuptools/_distutils/unixccompiler.py
setuptools/_distutils/util.py
setuptools/_distutils/version.py
setuptools/build_meta.py
setuptools/command/__init__.py
setuptools/config/__init__.py
setuptools/tests/integration/test_pip_install_sdist.py
setuptools/tests/test_windows_wrappers.py
tox.ini

index 284f7c1ecb71dc4be83820dfec554f938c6545fb..24e18c3ba7ed55a9e320df9b6faa3edcb64ab4be 100644 (file)
@@ -1,5 +1,5 @@
 [bumpversion]
-current_version = 63.1.0
+current_version = 63.3.0
 commit = True
 tag = True
 
index 7bd0af44d4c0d67d7e8b3e8d436bcc86cb6a43d2..83624a5bc4e5cec8c85a802ffde25b43ca52962d 100644 (file)
@@ -16,12 +16,10 @@ jobs:
         distutils:
         - local
         python:
-        # Build on pre-releases until stable, then stable releases.
-        # actions/setup-python#213
-        - ~3.7.0-0
-        - ~3.10.0-0
+        - 3.7-dev
+        - 3.10-dev
         # disabled due to #3365
-        # - ~3.11.0-0
+        # - 3.11-dev
         - pypy-3.7
         platform:
         - ubuntu-latest
@@ -151,7 +149,7 @@ jobs:
       - name: Setup Python
         uses: actions/setup-python@v3
         with:
-          python-version: "3.10"
+          python-version: "3.11-dev"
       - name: Install tox
         run: |
           python -m pip install tox
index c85d6dc9e19dc2d3cd2754e50ca252bf7e33eb82..48b5645ebc39cdbf8819e1f4fa47e9980bf98135 100644 (file)
@@ -1,3 +1,31 @@
+v63.3.0
+-------
+
+
+Changes
+^^^^^^^
+* #3460: <<<<<<< HEAD
+  Limit the scope of the _distutils_hack workaround for pip.
+  =======
+  Remove the pip workaround in _distutils_hack.
+  >>>>>>> 46344cf0 (Remove pip workaround in _distutils_hack.)
+* #3475: Merge with pypa/distutils@129480b, including substantial delinting and cleanup, some refactoring around compiler logic, better messaging in cygwincompiler (pypa/distutils#161).
+
+
+v63.2.0
+-------
+
+
+Changes
+^^^^^^^
+* #3395: Included a performance optimization: ``setuptools.build_meta`` no longer tries
+  to :func:`compile` the setup script code before :func:`exec`-ing it.
+
+Misc
+^^^^
+* #3435: Corrected issue in macOS framework builds on Python 3.9 not installed by homebrew (pypa/distutils#158).
+
+
 v63.1.0
 -------
 
diff --git a/changelog.d/3475.change.rst b/changelog.d/3475.change.rst
new file mode 100644 (file)
index 0000000..25f0b52
--- /dev/null
@@ -0,0 +1 @@
+Merge with pypa/distutils@129480b, including substantial delinting and cleanup, some refactoring around compiler logic, better messaging in cygwincompiler (pypa/distutils#161).
index 45a994fd6ba6c47aab3a8ee543f1cbaa095de906..3c778d800d8edc0c6ab9fdc15f3591e482ed9dfc 100644 (file)
@@ -126,7 +126,7 @@ If you put the following configuration in your ``pyproject.toml``:
 .. code-block:: toml
 
     [build-system]
-    requires = ["setuptools", "wheel"]
+    requires = ["setuptools"]
     build-backend = "backend"
     backend-path = ["_custom_build"]
 
index ebd0687a8e566fbb2cddc4f5a7ae4da81d2978b5..d9d97a9efe15c0a1f078da25b5e5476adcdd0168 100644 (file)
@@ -15,7 +15,7 @@ You could also run commands in other circumstances:
 
 * ``setuptools`` projects without ``setup.py`` (e.g., ``setup.cfg``-only)::
 
-   python -c "import setuptools; setup()" --help
+   python -c "from setuptools import setup; setup()" --help
 
 * ``distutils`` projects (with a ``setup.py`` importing ``distutils``)::
 
index aa638300de2e86f07ca16642d4828b217f0b7c27..5317058945747e975a7914381966bab8ebec0f8c 100644 (file)
@@ -151,7 +151,6 @@ To use this feature:
       [build-system]
       requires = [
         "setuptools >= 40.9.0",
-        "wheel",
       ]
       build-backend = "setuptools.build_meta"
 
index 6c39c3529cce62d4e3e46805a031a5b975ae234e..060288d8d1513c25fe8caf9a139d7535e82fcc91 100644 (file)
@@ -118,7 +118,7 @@ distributing into something that looks like the following
 
     mypackage
     ├── pyproject.toml
-    |   # setup.cfg or setup.py (depending on the confuguration method)
+    |   # setup.cfg or setup.py (depending on the configuration method)
     |   # README.rst or README.md (a nice description of your package)
     |   # LICENCE (properly chosen license information, e.g. MIT, BSD-3, GPL-3, MPL-2, etc...)
     └── mypackage
@@ -186,9 +186,9 @@ found, as shown in the example below:
     .. code-block:: ini
 
         [options]
-        packages = find: # OR `find_namespaces:` if you want to use namespaces
+        packages = find: # OR `find_namespace:` if you want to use namespaces
 
-        [options.packages.find] # (always `find` even if `find_namespaces:` was used before)
+        [options.packages.find] # (always `find` even if `find_namespace:` was used before)
         # This section is optional
         # Each entry in this section is optional, and if not specified, the default values are:
         # `where=.`, `include=*` and `exclude=` (empty).
index f6fdfc9e7c7f2e83aa7dbd2f4f2bcb11fcb0f02a..480b136839fb98a337dab75760add1cf2a27c596 100644 (file)
@@ -20,7 +20,7 @@ addopts = "--flake8"
 [tool.pytest-enabler.cov]
 addopts = "--cov"
 
-[pytest.enabler.xdist]
+[tool.pytest-enabler.xdist]
 addopts = "-n auto"
 
 [tool.towncrier]
index 65c87768b687af4aa66305923328300310b60edd..e99f12f3c3000d388290d561731bd93d6e3f3e3a 100644 (file)
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,6 +1,6 @@
 [metadata]
 name = setuptools
-version = 63.1.0
+version = 63.3.0
 author = Python Packaging Authority
 author_email = distutils-sig@python.org
 description = Easily download, build, install, upgrade, and uninstall Python packages
@@ -43,6 +43,8 @@ testing =
        pytest >= 6
        pytest-checkdocs >= 2.4
        pytest-flake8
+       # workaround for tholo/pytest-flake8#87
+       flake8 < 5
        pytest-black >= 0.3.7; \
                # workaround for jaraco/skeleton#22
                python_implementation != "PyPy"
index 3b5a8179bd69f1e27480224791ea7cc4a55802b0..aa0ceccbc6d93290a9d0f68875dceff301f7a6f8 100644 (file)
@@ -345,7 +345,7 @@ class MSVCCompiler(CCompiler):
 
         return list(map(make_out_path, source_filenames))
 
-    def compile(
+    def compile(  # noqa: C901
         self,
         sources,
         output_dir=None,
index 5a70c32c2f84c139c18d88dbc263a2fd8f5b53fc..4cb9bf39324daa51148207cf8b23f83885bd075d 100644 (file)
@@ -134,7 +134,7 @@ def make_tarball(
     return archive_name
 
 
-def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
+def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):  # noqa: C901
     """Create a zip file from all the files under 'base_dir'.
 
     The output zip file will be named 'base_name' + ".zip".  Uses either the
index 056b2d98d9680c891b7409cceeff07a1d047c545..7a6f951fa83793aaf6db7e26f5b6c5a8caaac86a 100644 (file)
@@ -77,7 +77,7 @@ class BCPPCompiler(CCompiler):
 
     # -- Worker methods ------------------------------------------------
 
-    def compile(
+    def compile(  # noqa: C901
         self,
         sources,
         output_dir=None,
@@ -174,7 +174,7 @@ class BCPPCompiler(CCompiler):
 
     # create_static_lib ()
 
-    def link(
+    def link(  # noqa: C901
         self,
         target_desc,
         objects,
@@ -250,8 +250,8 @@ class BCPPCompiler(CCompiler):
                 else:
                     objects.append(file)
 
-            for l in library_dirs:
-                ld_args.append("/L%s" % os.path.normpath(l))
+            for ell in library_dirs:
+                ld_args.append("/L%s" % os.path.normpath(ell))
             ld_args.append("/L.")  # we sometimes use relative paths
 
             # list of object files
index 005b64acdaca271f44da65b2722b063678527a50..c1761d0214411d11be4bec6318155e0d8b0000c4 100644 (file)
@@ -3,8 +3,16 @@
 Contains CCompiler, an abstract base class that defines the interface
 for the Distutils compiler abstraction model."""
 
-import sys, os, re
-from distutils.errors import *
+import sys
+import os
+import re
+from distutils.errors import (
+    CompileError,
+    LinkError,
+    UnknownFileError,
+    DistutilsPlatformError,
+    DistutilsModuleError,
+)
 from distutils.spawn import spawn
 from distutils.file_util import move_file
 from distutils.dir_util import mkpath
@@ -808,7 +816,7 @@ class CCompiler:
         """
         raise NotImplementedError
 
-    def has_function(
+    def has_function(  # noqa: C901
         self,
         funcname,
         includes=None,
@@ -945,10 +953,9 @@ int main (int argc, char **argv) {
         self, libname, lib_type='static', strip_dir=0, output_dir=''  # or 'shared'
     ):
         assert output_dir is not None
-        if lib_type not in ("static", "shared", "dylib", "xcode_stub"):
-            raise ValueError(
-                "'lib_type' must be \"static\", \"shared\", \"dylib\", or \"xcode_stub\""
-            )
+        expected = '"static", "shared", "dylib", "xcode_stub"'
+        if lib_type not in eval(expected):
+            raise ValueError(f"'lib_type' must be {expected}")
         fmt = getattr(self, lib_type + "_lib_format")
         ext = getattr(self, lib_type + "_lib_extension")
 
index 4a9bcc2a733f77d3c6202311f8a2966e7c0630b3..6f68801db8769a44b8432d5070912ee61b900f25 100644 (file)
@@ -4,7 +4,9 @@ Provides the Command class, the base class for the command classes
 in the distutils.command package.
 """
 
-import sys, os, re
+import sys
+import os
+import re
 from distutils.errors import DistutilsOptionError
 from distutils import util, dir_util, file_util, archive_util, dep_util
 from distutils import log
index d199c24277dea07bf3f3fe4aa0f50c6b43ebc242..a40c1f9471fc2a9a9bdf9573cb15a3de952158f2 100644 (file)
@@ -3,7 +3,7 @@
 Package containing implementation of all the standard Distutils
 commands."""
 
-__all__ = [
+__all__ = [  # noqa: F822
     'build',
     'build_py',
     'build_ext',
@@ -23,10 +23,4 @@ __all__ = [
     'bdist_wininst',
     'check',
     'upload',
-    # These two are reserved for future use:
-    #'bdist_sdux',
-    #'bdist_pkgtool',
-    # Note:
-    # bdist_packager is not included because it only provides
-    # an abstract base class
 ]
index e032603a9df5dca9b07bc1cf91651e57c48330bb..cffa27cb08285d1535e9812858dbad1551fc972f 100644 (file)
@@ -7,18 +7,21 @@ import sys
 import os
 import functools
 import subprocess
+import sysconfig
 
 
 @functools.lru_cache()
 def enabled():
     """
-    Only enabled for Python 3.9 framework builds except ensurepip and venv.
+    Only enabled for Python 3.9 framework homebrew builds
+    except ensurepip and venv.
     """
     PY39 = (3, 9) < sys.version_info < (3, 10)
     framework = sys.platform == 'darwin' and sys._framework
+    homebrew = "Cellar" in sysconfig.get_config_var('projectbase')
     venv = sys.prefix != sys.base_prefix
     ensurepip = os.environ.get("ENSUREPIP_OPTIONS")
-    return PY39 and framework and not venv and not ensurepip
+    return PY39 and framework and homebrew and not venv and not ensurepip
 
 
 schemes = dict(
index 2a639761c03642f1628925fb81cf1a9f8f33727d..53f1321450a31a6bb2007258b0f7563fca344645 100644 (file)
@@ -5,7 +5,7 @@ distribution)."""
 
 import os
 from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import DistutilsPlatformError, DistutilsOptionError
 from distutils.util import get_platform
 
 
@@ -15,11 +15,17 @@ def show_formats():
 
     formats = []
     for format in bdist.format_commands:
-        formats.append(("formats=" + format, None, bdist.format_command[format][1]))
+        formats.append(("formats=" + format, None, bdist.format_commands[format][1]))
     pretty_printer = FancyGetopt(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"
@@ -64,31 +70,23 @@ class bdist(Command):
     # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
     default_format = {'posix': 'gztar', 'nt': 'zip'}
 
-    # Establish the preferred order (for the --help-formats option).
-    format_commands = [
-        'rpm',
-        'gztar',
-        'bztar',
-        'xztar',
-        'ztar',
-        'tar',
-        'wininst',
-        'zip',
-        'msi',
-    ]
-
-    # And the real information.
-    format_command = {
-        '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"),
-    }
+    # 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"),
+        }
+    )
+
+    # for compatibility until Setuptools references only format_commands
+    format_command = format_commands
 
     def initialize_options(self):
         self.bdist_base = None
@@ -132,7 +130,7 @@ class bdist(Command):
         commands = []
         for format in self.formats:
             try:
-                commands.append(self.format_command[format][0])
+                commands.append(self.format_commands[format][0])
             except KeyError:
                 raise DistutilsOptionError("invalid format '%s'" % format)
 
index 3c387828670b05616b10cab2aaf77f779c45c392..d3f519e07876b100b63323bc3114050236c166a5 100644 (file)
@@ -8,7 +8,7 @@ import os
 from distutils.core import Command
 from distutils.util import get_platform
 from distutils.dir_util import remove_tree, ensure_relative
-from distutils.errors import *
+from distutils.errors import DistutilsPlatformError
 from distutils.sysconfig import get_python_version
 from distutils import log
 
index 2f292c960060cf3e2ad01fdccccaa8580a647f0d..6e1e1abd86a92fdc61ecab2962171c52172a3b25 100644 (file)
@@ -31,9 +31,6 @@ class PyDialog(Dialog):
         default, cancel, bitmap=true)"""
         super().__init__(*args)
         ruler = self.h - 36
-        bmwidth = 152 * ruler / 328
-        # if kw.get("bitmap", True):
-        #    self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
         self.line("BottomLine", 0, ruler, self.w, 0)
 
     def title(self, title):
@@ -231,7 +228,7 @@ class bdist_msi(Command):
                 )
         self.install_script_key = None
 
-    def run(self):
+    def run(self):  # noqa: C901
         if not self.skip_build:
             self.run_command('build')
 
@@ -318,7 +315,7 @@ class bdist_msi(Command):
         if not self.keep_temp:
             remove_tree(self.bdist_dir, dry_run=self.dry_run)
 
-    def add_files(self):
+    def add_files(self):  # noqa: C901
         db = self.db
         cab = msilib.CAB("distfiles")
         rootdir = os.path.abspath(self.bdist_dir)
@@ -406,11 +403,9 @@ class bdist_msi(Command):
             exe_action = "PythonExe" + ver
             target_dir_prop = "TARGETDIR" + ver
             exe_prop = "PYTHON" + ver
-            if msilib.Win64:
-                # type: msidbLocatorTypeRawValue + msidbLocatorType64bit
-                Type = 2 + 16
-            else:
-                Type = 2
+
+            # Type: msidbLocatorTypeRawValue + msidbLocatorType64bit
+            Type = 2 + 16 * bool(msilib.Win64)
             add_data(
                 self.db,
                 "RegLocator",
@@ -517,7 +512,6 @@ class bdist_msi(Command):
         # see "Dialog Style Bits"
         modal = 3  # visible | modal
         modeless = 1  # visible
-        track_disk_space = 32
 
         # UI customization properties
         add_data(
@@ -590,7 +584,9 @@ class bdist_msi(Command):
             320,
             80,
             0x30003,
-            "[ProductName] setup ended prematurely because of an error.  Your system has not been modified.  To install this program at a later time, please run the installation again.",
+            "[ProductName] setup ended prematurely because of an error. "
+            "Your system has not been modified.  To install this program "
+            "at a later time, please run the installation again.",
         )
         fatal.text(
             "Description2",
@@ -618,7 +614,8 @@ class bdist_msi(Command):
             80,
             0x30003,
             "[ProductName] setup was interrupted.  Your system has not been modified.  "
-            "To install this program at a later time, please run the installation again.",
+            "To install this program at a later time, please run the installation "
+            "again.",
         )
         user_exit.text(
             "Description2",
@@ -683,7 +680,10 @@ class bdist_msi(Command):
             330,
             50,
             3,
-            "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.",
+            "The following applications are using files that need to be updated by "
+            "this "
+            "setup. Close these applications and then click Retry to continue the "
+            "installation or Cancel to exit it.",
         )
         inuse.control(
             "List",
@@ -720,7 +720,6 @@ class bdist_msi(Command):
             None,
         )
         error.text("ErrorText", 50, 9, 280, 48, 3, "")
-        # error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None)
         error.pushbutton("N", 120, 72, 81, 21, 3, "No", None).event(
             "EndDialog", "ErrorNo"
         )
@@ -785,7 +784,8 @@ class bdist_msi(Command):
             194,
             30,
             3,
-            "Please wait while the installer finishes determining your disk space requirements.",
+            "Please wait while the installer finishes determining your disk space "
+            "requirements.",
         )
         c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None)
         c.event("EndDialog", "Exit")
@@ -802,7 +802,8 @@ class bdist_msi(Command):
             320,
             40,
             0x30003,
-            "Please wait while the Installer prepares to guide you through the installation.",
+            "Please wait while the Installer prepares to guide you through the "
+            "installation.",
         )
         prep.title("Welcome to the [ProductName] Installer")
         c = prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...")
@@ -1096,7 +1097,6 @@ class bdist_msi(Command):
 
         # Close dialog when maintenance action scheduled
         c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20)
-        # c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21)
 
         maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg")
 
index cf4b95258c923a28a04c1c5b6f8f75c14267c86a..fcfd7cd8fe648b09576c8dabfd3cd1ef6dde2854 100644 (file)
@@ -3,11 +3,19 @@
 Implements the Distutils 'bdist_rpm' command (create RPM source and binary
 distributions)."""
 
-import subprocess, sys, os
+import subprocess
+import sys
+import os
+
 from distutils.core import Command
 from distutils.debug import DEBUG
 from distutils.file_util import write_file
-from distutils.errors import *
+from distutils.errors import (
+    DistutilsOptionError,
+    DistutilsPlatformError,
+    DistutilsFileError,
+    DistutilsExecError,
+)
 from distutils.sysconfig import get_python_version
 from distutils import log
 
@@ -268,7 +276,7 @@ class bdist_rpm(Command):
 
         self.ensure_string('force_arch')
 
-    def run(self):
+    def run(self):  # noqa: C901
         if DEBUG:
             print("before _get_package_data():")
             print("vendor =", self.vendor)
@@ -359,12 +367,12 @@ class bdist_rpm(Command):
                 line = out.readline()
                 if not line:
                     break
-                l = line.strip().split()
-                assert len(l) == 2
-                binary_rpms.append(l[1])
+                ell = line.strip().split()
+                assert len(ell) == 2
+                binary_rpms.append(ell[1])
                 # The source rpm is named after the first entry in the spec file
                 if source_rpm is None:
-                    source_rpm = l[0]
+                    source_rpm = ell[0]
 
             status = out.close()
             if status:
@@ -401,7 +409,7 @@ class bdist_rpm(Command):
     def _dist_path(self, path):
         return os.path.join(self.dist_dir, os.path.basename(path))
 
-    def _make_spec_file(self):
+    def _make_spec_file(self):  # noqa: C901
         """Generate the text of an RPM spec file and return it as a
         list of strings (one per line).
         """
index 76b8a890df2046f4ddb94678055e3e7f52f88527..7e9a64a5bc7c7fcd21975d1e16799b6cf43cc056 100644 (file)
@@ -9,7 +9,7 @@ import warnings
 from distutils.core import Command
 from distutils.util import get_platform
 from distutils.dir_util import remove_tree
-from distutils.errors import *
+from distutils.errors import DistutilsOptionError, DistutilsPlatformError
 from distutils.sysconfig import get_python_version
 from distutils import log
 
@@ -357,7 +357,7 @@ class bdist_wininst(Command):
             )
         return installer_name
 
-    def get_exe_bytes(self):
+    def get_exe_bytes(self):  # noqa: C901
         # If a target-version other than the current version has been
         # specified, then using the MSVC version from *this* build is no good.
         # Without actually finding and executing the target version and parsing
index 3aa7fac71b2a0eaec02db9c2a0d2c79886456d6c..e4b064250cf074cdb5568d7b19ca89f2f14a07d6 100644 (file)
@@ -2,7 +2,8 @@
 
 Implements the Distutils 'build' command."""
 
-import sys, os
+import sys
+import os
 from distutils.core import Command
 from distutils.errors import DistutilsOptionError
 from distutils.util import get_platform
@@ -65,7 +66,7 @@ class build(Command):
         self.executable = None
         self.parallel = None
 
-    def finalize_options(self):
+    def finalize_options(self):  # noqa: C901
         if self.plat_name is None:
             self.plat_name = get_platform()
         else:
index 003499fa9765d62d2197b01bc7466eb11d1475aa..50bb9bbabb7ab00cd4763b524ab536e711e468a8 100644 (file)
@@ -16,7 +16,7 @@ module."""
 
 import os
 from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import DistutilsSetupError
 from distutils.sysconfig import customize_compiler
 from distutils import log
 
index 1a6dd39400eb75037c9dc88ffa8b4c595a05b2a0..153a0b6dc132d2d92cf9870fcb8fc6dda1487d2c 100644 (file)
@@ -9,7 +9,14 @@ import os
 import re
 import sys
 from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import (
+    DistutilsOptionError,
+    DistutilsSetupError,
+    CCompilerError,
+    DistutilsError,
+    CompileError,
+    DistutilsPlatformError,
+)
 from distutils.sysconfig import customize_compiler, get_python_version
 from distutils.sysconfig import get_config_h_filename
 from distutils.dep_util import newer_group
@@ -124,7 +131,7 @@ class build_ext(Command):
         self.user = None
         self.parallel = None
 
-    def finalize_options(self):
+    def finalize_options(self):  # noqa: C901
         from distutils import sysconfig
 
         self.set_undefined_options(
@@ -272,7 +279,7 @@ class build_ext(Command):
             except ValueError:
                 raise DistutilsOptionError("parallel should be an integer")
 
-    def run(self):
+    def run(self):  # noqa: C901
         from distutils.ccompiler import new_compiler
 
         # 'self.extensions', as supplied by setup.py, is a list of
@@ -338,7 +345,7 @@ class build_ext(Command):
         # Now actually compile and link everything.
         self.build_extensions()
 
-    def check_extensions_list(self, extensions):
+    def check_extensions_list(self, extensions):  # noqa: C901
         """Ensure that the list of extensions (presumably provided as a
         command option 'extensions') is valid, i.e. it is a list of
         Extension objects.  We also support the old-style list of 2-tuples,
@@ -724,7 +731,7 @@ class build_ext(Command):
             ext.export_symbols.append(initfunc_name)
         return ext.export_symbols
 
-    def get_libraries(self, ext):
+    def get_libraries(self, ext):  # noqa: C901
         """Return the list of libraries to link against when building a
         shared extension.  On most platforms, this is just 'ext.libraries';
         on Windows, we add the Python library (eg. python20.dll).
index 7723d359dba374a664c253da1e1d5209b5583ef9..47c6158e0f74033bfcfeb7424df227a3815651de 100644 (file)
@@ -8,7 +8,7 @@ import sys
 import glob
 
 from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import DistutilsOptionError, DistutilsFileError
 from distutils.util import convert_path
 from distutils import log
 
@@ -137,7 +137,6 @@ class build_py(Command):
 
     def build_package_data(self):
         """Copy data files into build directory"""
-        lastdir = None
         for package, src_dir, build_dir, filenames in self.data_files:
             for filename in filenames:
                 target = os.path.join(build_dir, filename)
index 17058dbf6dc06c05a256a1898daba6b1816e267f..2cc5d1e09c09b6c674d47a26c5ebc6163705ecce 100644 (file)
@@ -75,7 +75,7 @@ class build_scripts(Command):
 
         return outfiles, updated_files
 
-    def _copy_script(self, script, outfiles, updated_files):
+    def _copy_script(self, script, outfiles, updated_files):  # noqa: C901
         shebang_match = None
         script = convert_path(script)
         outfile = os.path.join(self.build_dir, os.path.basename(script))
index 176a8b876469892029e4e0a6261aebed13311ca2..9c3523a858048e5f063e4c0665526e7ef14b41f5 100644 (file)
@@ -2,8 +2,6 @@
 
 Implements the Distutils 'check' command.
 """
-from email.utils import getaddresses
-
 from distutils.core import Command
 from distutils.errors import DistutilsSetupError
 
index 73de1d3ec81d87bfde2b77f43662b0d1caf7d5e1..4492c89660c202acf882375258dffafff00a99ba 100644 (file)
@@ -9,7 +9,8 @@ configure-like tasks: "try to compile this C code", or "figure out where
 this header file lives".
 """
 
-import os, re
+import os
+import re
 
 from distutils.core import Command
 from distutils.errors import DistutilsExecError
index 7d9054e33f9a76e89bfc0c5ced9ff26abfa8bb47..a38cddcda5380aac99bade87e2cdf95d4c99348a 100644 (file)
@@ -12,11 +12,10 @@ from distutils import log
 from distutils.core import Command
 from distutils.debug import DEBUG
 from distutils.sysconfig import get_config_vars
-from distutils.errors import DistutilsPlatformError
 from distutils.file_util import write_file
 from distutils.util import convert_path, subst_vars, change_root
 from distutils.util import get_platform
-from distutils.errors import DistutilsOptionError
+from distutils.errors import DistutilsOptionError, DistutilsPlatformError
 from . import _framework_compat as fw
 from .. import _collections
 
@@ -36,8 +35,10 @@ WINDOWS_SCHEME = {
 INSTALL_SCHEMES = {
     'posix_prefix': {
         'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',
-        'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}/site-packages',
-        'headers': '{base}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',
+        'platlib': '{platbase}/{platlibdir}/{implementation_lower}'
+        '{py_version_short}/site-packages',
+        'headers': '{base}/include/{implementation_lower}'
+        '{py_version_short}{abiflags}/{dist_name}',
         'scripts': '{base}/bin',
         'data': '{base}',
     },
@@ -70,7 +71,8 @@ if HAS_USER_SITE:
     INSTALL_SCHEMES['nt_user'] = {
         'purelib': '{usersite}',
         'platlib': '{usersite}',
-        'headers': '{userbase}/{implementation}{py_version_nodot_plat}/Include/{dist_name}',
+        'headers': '{userbase}/{implementation}{py_version_nodot_plat}'
+        '/Include/{dist_name}',
         'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
         'data': '{userbase}',
     }
@@ -78,7 +80,8 @@ if HAS_USER_SITE:
     INSTALL_SCHEMES['posix_user'] = {
         'purelib': '{usersite}',
         'platlib': '{usersite}',
-        'headers': '{userbase}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',
+        'headers': '{userbase}/include/{implementation_lower}'
+        '{py_version_short}{abiflags}/{dist_name}',
         'scripts': '{userbase}/bin',
         'data': '{userbase}',
     }
@@ -327,7 +330,7 @@ class install(Command):
     # party Python modules on various platforms given a wide
     # array of user input is decided.  Yes, it's quite complex!)
 
-    def finalize_options(self):
+    def finalize_options(self):  # noqa: C901
         """Finalizes options."""
         # This method (and its helpers, like 'finalize_unix()',
         # 'finalize_other()', and 'select_scheme()') is where the default
index dc939633ee9e2cdd22a9fe91a8edd981bf956097..d5e68a6e47199372c79ec094e0385f49a6600f22 100644 (file)
@@ -1,12 +1,16 @@
-"""distutils.command.install_egg_info
+"""
+distutils.command.install_egg_info
 
 Implements the Distutils 'install_egg_info' command, for installing
-a package's PKG-INFO metadata."""
+a package's PKG-INFO metadata.
+"""
 
+import os
+import sys
+import re
 
 from distutils.cmd import Command
 from distutils import log, dir_util
-import os, sys, re
 
 
 class install_egg_info(Command):
index ca407eb70396cb036e754dc23143bbf555316fc2..d2351ab8bfaaae6f22e069533ab483fcbaa8a1db 100644 (file)
@@ -7,11 +7,11 @@ Implements the Distutils 'register' command (register with the repository).
 
 import getpass
 import io
-import urllib.parse, urllib.request
+import urllib.parse
+import urllib.request
 from warnings import warn
 
 from distutils.core import PyPIRCCommand
-from distutils.errors import *
 from distutils import log
 
 
@@ -104,7 +104,7 @@ class register(PyPIRCCommand):
         (code, result) = self.post_to_server(self.build_post_data('verify'))
         log.info('Server response (%s): %s', code, result)
 
-    def send_metadata(self):
+    def send_metadata(self):  # noqa: C901
         '''Send the metadata to the package index server.
 
         Well, do the following:
@@ -261,7 +261,7 @@ Your selection [default 1]: ''',
             data['metadata_version'] = '1.1'
         return data
 
-    def post_to_server(self, data, auth=None):
+    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(
index aad3e7134c05a62c279a5a2a0d55e4ec74888221..ec3c97ac7212159d464ca12874a9364437a70a0a 100644 (file)
@@ -15,7 +15,7 @@ from distutils.text_file import TextFile
 from distutils.filelist import FileList
 from distutils import log
 from distutils.util import convert_path
-from distutils.errors import DistutilsTemplateError, DistutilsOptionError
+from distutils.errors import DistutilsOptionError, DistutilsTemplateError
 
 
 def show_formats():
index 782e3dea96509a5a274cc37856871b2f4b8626d5..f2a8118e325df1ab827f798bd46b380a78e947a5 100644 (file)
@@ -71,7 +71,7 @@ class upload(PyPIRCCommand):
         for command, pyversion, filename in self.distribution.dist_files:
             self.upload_file(command, pyversion, filename)
 
-    def upload_file(self, command, pyversion, filename):
+    def upload_file(self, command, pyversion, filename):  # noqa: C901
         # Makes sure the repository URL is compliant
         schema, netloc, url, params, query, fragments = urlparse(self.repository)
         if params or query or fragments:
index 34a1c3b7c9e81f7d0228e5c9836c9c22788347ae..6e0c3a71f10cf216aaa19053564159353e47e66a 100644 (file)
@@ -44,7 +44,7 @@ class PyPIRCCommand(Command):
         with os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f:
             f.write(DEFAULT_PYPIRC % (username, password))
 
-    def _read_pypirc(self):
+    def _read_pypirc(self):  # noqa: C901
         """Reads the .pypirc file."""
         rc = self._get_rc_file()
         if os.path.exists(rc):
index 305ecf6922f4511492c74b6a79abb32264e52a55..333596acc75a7bb5dec67a7ea1a305a241e092bc 100644 (file)
@@ -11,7 +11,12 @@ import sys
 import tokenize
 
 from distutils.debug import DEBUG
-from distutils.errors import *
+from distutils.errors import (
+    DistutilsSetupError,
+    DistutilsError,
+    CCompilerError,
+    DistutilsArgError,
+)
 
 # Mainly import these so setup scripts can "from distutils.core import" them.
 from distutils.dist import Distribution
@@ -19,6 +24,9 @@ from distutils.cmd import Command
 from distutils.config import PyPIRCCommand
 from distutils.extension import Extension
 
+
+__all__ = ['Distribution', 'Command', 'PyPIRCCommand', 'Extension', 'setup']
+
 # This is a barebones help message generated displayed when the user
 # runs the setup script with no arguments at all.  More useful help
 # is generated with various --help options: global help, list commands,
@@ -33,7 +41,7 @@ usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
 
 def gen_usage(script_name):
     script = os.path.basename(script_name)
-    return USAGE % vars()
+    return USAGE % locals()
 
 
 # Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
@@ -85,7 +93,7 @@ extension_keywords = (
 )
 
 
-def setup(**attrs):
+def setup(**attrs):  # noqa: C901
     """The gateway to the Distutils: do everything your setup script needs
     to do, in a highly flexible and user-driven way.  Briefly: create a
     Distribution instance; find and parse config files; parse the command
index 445e2e51e5054c871ca88f498dec1d5004d61681..e376446f1bfb8c4995f52f8d492ee168c927fb6d 100644 (file)
@@ -101,6 +101,12 @@ def get_msvcr():
             raise ValueError("Unknown MS Compiler version %s " % msc_ver)
 
 
+_runtime_library_dirs_msg = (
+    "Unable to set runtime library search path on Windows, "
+    "usually indicated by `runtime_library_dirs` parameter to Extension"
+)
+
+
 class CygwinCCompiler(UnixCCompiler):
     """Handles the Cygwin port of the GNU C compiler to Windows."""
 
@@ -199,10 +205,7 @@ class CygwinCCompiler(UnixCCompiler):
         objects = copy.copy(objects or [])
 
         if runtime_library_dirs:
-            self.warn(
-                "I don't know what to do with 'runtime_library_dirs': "
-                + str(runtime_library_dirs)
-            )
+            self.warn(_runtime_library_dirs_msg)
 
         # Additional libraries
         libraries.extend(self.dll_libraries)
@@ -228,7 +231,6 @@ class CygwinCCompiler(UnixCCompiler):
 
             # generate the filenames for these files
             def_file = os.path.join(temp_dir, dll_name + ".def")
-            lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
 
             # Generate .def file
             contents = ["LIBRARY %s" % os.path.basename(output_filename), "EXPORTS"]
@@ -236,10 +238,8 @@ class CygwinCCompiler(UnixCCompiler):
                 contents.append(sym)
             self.execute(write_file, (def_file, contents), "writing %s" % def_file)
 
-            # next add options for def-file and to creating import libraries
+            # next add options for def-file
 
-            # doesn't work: bfd_close build\...\libfoo.a: Invalid operation
-            # extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
             # for gcc/ld the def-file is specified as any object files
             objects.append(def_file)
 
@@ -276,7 +276,7 @@ class CygwinCCompiler(UnixCCompiler):
         # cygwin doesn't support rpath. While in theory we could error
         # out like MSVC does, code might expect it to work like on Unix, so
         # just warn and hope for the best.
-        self.warn("don't know how to set runtime library search path on Windows")
+        self.warn(_runtime_library_dirs_msg)
         return []
 
     # -- Miscellaneous methods -----------------------------------------
@@ -340,9 +340,7 @@ class Mingw32CCompiler(CygwinCCompiler):
         self.dll_libraries = get_msvcr()
 
     def runtime_library_dir_option(self, dir):
-        raise DistutilsPlatformError(
-            "don't know how to set runtime library search path on Windows"
-        )
+        raise DistutilsPlatformError(_runtime_library_dirs_msg)
 
 
 # Because these compilers aren't configured in Python's pyconfig.h file by
index d94e111ca6c4ae6dc35bc36ccf094f1c0ccb34f6..db1fa01996ce0d47cd7f070c53b085926440d377 100644 (file)
@@ -82,9 +82,9 @@ def newer_group(sources, target, missing='error'):
             if missing == 'error':  # blow up when we stat() the file
                 pass
             elif missing == 'ignore':  # missing source dropped from
-                continue  #  target's dependency list
+                continue  # target's dependency list
             elif missing == 'newer':  # missing source means target is
-                return 1  #  out-of-date
+                return 1  # out-of-date
 
         source_mtime = os.stat(source)[ST_MTIME]
         if source_mtime > target_mtime:
index 2c19b9833cb2c3508b871f65e548146cf2e5adcb..7a132e314408591ba7599ea006c1b63e6f8a6105 100644 (file)
@@ -4,17 +4,15 @@ Utility functions for manipulating directories and directory trees."""
 
 import os
 import errno
-from distutils.errors import DistutilsFileError, DistutilsInternalError
+from distutils.errors import DistutilsInternalError, DistutilsFileError
 from distutils import log
 
 # cache for by mkpath() -- in addition to cheapening redundant calls,
 # eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
 _path_created = {}
 
-# I don't use os.makedirs because a) it's new to Python 1.5.2, and
-# b) it blows up if the directory already exists (I want to silently
-# succeed in that case).
-def mkpath(name, mode=0o777, verbose=1, dry_run=0):
+
+def mkpath(name, mode=0o777, verbose=1, dry_run=0):  # noqa: C901
     """Create a directory and any missing ancestor directories.
 
     If the directory already exists (or if 'name' is the empty string, which
@@ -23,6 +21,12 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0):
     (eg. some sub-path exists, but is a file rather than a directory).
     If 'verbose' is true, print a one-line summary of each mkdir to stdout.
     Return the list of directories actually created.
+
+    os.makedirs is not used because:
+
+    a) It's new to Python 1.5.2, and
+    b) it blows up if the directory already exists (in which case it should
+       silently succeed).
     """
 
     global _path_created
@@ -100,7 +104,7 @@ def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
         mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
 
 
-def copy_tree(
+def copy_tree(  # noqa: C901
     src,
     dst,
     preserve_mode=1,
index 82e3684daaa911dcb542cce847b8354e242385da..b4535eb75eb4a75daf3a3d1beb1c69e8f64d7ae6 100644 (file)
@@ -14,7 +14,12 @@ try:
 except ImportError:
     warnings = None
 
-from distutils.errors import *
+from distutils.errors import (
+    DistutilsOptionError,
+    DistutilsModuleError,
+    DistutilsArgError,
+    DistutilsClassError,
+)
 from distutils.fancy_getopt import FancyGetopt, translate_longopt
 from distutils.util import check_environ, strtobool, rfc822_escape
 from distutils import log
@@ -116,7 +121,7 @@ Common commands: (see '--help-commands' for more)
 
     # -- Creation/initialization methods -------------------------------
 
-    def __init__(self, attrs=None):
+    def __init__(self, attrs=None):  # noqa: C901
         """Construct a new Distribution instance: initialize all the
         attributes of a Distribution, and then use 'attrs' (a dictionary
         mapping attribute names to values) to assign some of those
@@ -359,7 +364,7 @@ Common commands: (see '--help-commands' for more)
 
         return files
 
-    def parse_config_files(self, filenames=None):
+    def parse_config_files(self, filenames=None):  # noqa: C901
         from configparser import ConfigParser
 
         # Ignore install directory options if we have a venv
@@ -508,7 +513,7 @@ Common commands: (see '--help-commands' for more)
             ),
         ]
 
-    def _parse_command_opts(self, parser, args):
+    def _parse_command_opts(self, parser, args):  # noqa: C901
         """Parse the command-line options for a single command.
         'parser' must be a FancyGetopt instance; 'args' must be the list
         of arguments, starting with the current command (whose options
@@ -871,7 +876,7 @@ Common commands: (see '--help-commands' for more)
 
         return cmd_obj
 
-    def _set_command_options(self, command_obj, option_dict=None):
+    def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
         """Set the options for 'command_obj' from 'option_dict'.  Basically
         this means copying elements of a dictionary ('option_dict') to
         attributes of an instance ('command').
index b05c5d909fcebaa994f81efa018e0a177c81551e..dff2be9edfc34c35f9cdcb97e009b0e122f50dd9 100644 (file)
@@ -142,7 +142,7 @@ class Extension:
         )
 
 
-def read_setup_file(filename):
+def read_setup_file(filename):  # noqa: C901
     """Reads a Setup file and returns Extension instances."""
     from distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx
 
index b9b21766e161ebbdb9fc7366cf5ab839cc632e62..9ee06420deb75c1f429862f3cf42f7328284c71a 100644 (file)
@@ -8,9 +8,11 @@ additional features:
   * options set attributes of a passed-in object
 """
 
-import sys, string, re
+import sys
+import string
+import re
 import getopt
-from distutils.errors import *
+from distutils.errors import DistutilsGetoptError, DistutilsArgError
 
 # Much like command_re in distutils.core, this is close to but not quite
 # the same as a Python NAME -- except, in the spirit of most GNU
@@ -136,7 +138,7 @@ class FancyGetopt:
         self._check_alias_dict(negative_alias, "negative alias")
         self.negative_alias = negative_alias
 
-    def _grok_option_table(self):
+    def _grok_option_table(self):  # noqa: C901
         """Populate the various data structures that keep tabs on the
         option table.  Called by 'getopt()' before it can do anything
         worthwhile.
@@ -218,7 +220,7 @@ class FancyGetopt:
                 self.short_opts.append(short)
                 self.short2long[short[0]] = long
 
-    def getopt(self, args=None, object=None):
+    def getopt(self, args=None, object=None):  # noqa: C901
         """Parse command-line options in args. Store as attributes on object.
 
         If 'args' is None or not supplied, uses 'sys.argv[1:]'.  If
@@ -289,7 +291,7 @@ class FancyGetopt:
         else:
             return self.option_order
 
-    def generate_help(self, header=None):
+    def generate_help(self, header=None):  # noqa: C901
         """Generate help text (a list of strings, one per suggested line of
         output) from the option table for this FancyGetopt object.
         """
@@ -301,13 +303,13 @@ class FancyGetopt:
         for option in self.option_table:
             long = option[0]
             short = option[1]
-            l = len(long)
+            ell = len(long)
             if long[-1] == '=':
-                l = l - 1
+                ell = ell - 1
             if short is not None:
-                l = l + 5  # " (-x)" where short == 'x'
-            if l > max_opt:
-                max_opt = l
+                ell = ell + 5  # " (-x)" where short == 'x'
+            if ell > max_opt:
+                max_opt = ell
 
         opt_width = max_opt + 2 + 2 + 2  # room for indent + dashes + gutter
 
@@ -363,8 +365,8 @@ class FancyGetopt:
                 else:
                     lines.append("  --%-*s" % opt_names)
 
-            for l in text[1:]:
-                lines.append(big_indent + l)
+            for ell in text[1:]:
+                lines.append(big_indent + ell)
         return lines
 
     def print_help(self, header=None, file=None):
@@ -405,11 +407,11 @@ def wrap_text(text, width):
         cur_len = 0  # length of current line
 
         while chunks:
-            l = len(chunks[0])
-            if cur_len + l <= width:  # can squeeze (at least) this chunk in
+            ell = len(chunks[0])
+            if cur_len + ell <= width:  # can squeeze (at least) this chunk in
                 cur_line.append(chunks[0])
                 del chunks[0]
-                cur_len = cur_len + l
+                cur_len = cur_len + ell
             else:  # this line is full
                 # drop last chunk if all space
                 if cur_line and cur_line[-1][0] == ' ':
index 4ff2230c000b838ea182ace9935af87cb85b5f3a..0662fe40f3fa90647959289d9749f4843ad29cfe 100644 (file)
@@ -11,7 +11,7 @@ from distutils import log
 _copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'}
 
 
-def _copy_file_contents(src, dst, buffer_size=16 * 1024):
+def _copy_file_contents(src, dst, buffer_size=16 * 1024):  # noqa: C901
     """Copy the file 'src' to 'dst'; both must be filenames.  Any error
     opening either file, reading from 'src', or writing to 'dst', raises
     DistutilsFileError.  Data is read/written in chunks of 'buffer_size'
@@ -65,7 +65,7 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024):
             fsrc.close()
 
 
-def copy_file(
+def copy_file(  # noqa: C901
     src,
     dst,
     preserve_mode=1,
@@ -173,7 +173,7 @@ def copy_file(
 
 
 # XXX I suspect this is Unix-specific -- need porting help!
-def move_file(src, dst, verbose=1, dry_run=0):
+def move_file(src, dst, verbose=1, dry_run=0):  # noqa: C901
 
     """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
     be moved into it with the same name; otherwise, 'src' is just renamed
index 37ab341e9010b5d6b918669ae98d0ef2f7e936f4..4396d9dee5acf762cdaa0576569cbe7361c72569 100644 (file)
@@ -105,7 +105,7 @@ class FileList:
 
         return (action, patterns, dir, dir_pattern)
 
-    def process_template_line(self, line):
+    def process_template_line(self, line):  # noqa: C901
         # Parse the line: split it up, make sure the right number of words
         # is there, and return the relevant words.  'action' is always
         # defined: it's the first word of the line.  Which of the other
index 225f1a2f52da774b36049e0ec38a7fe90d1c3473..276e137916aee79013e89e91285782cf70dc7edb 100644 (file)
@@ -350,7 +350,7 @@ class MSVCCompiler(CCompiler):
         self.__arch = None  # deprecated name
         self.initialized = False
 
-    def initialize(self, plat_name=None):
+    def initialize(self, plat_name=None):  # noqa: C901
         # multi-init means we would need to check platform same each time...
         assert not self.initialized, "don't init multiple times"
         if self.__version < 8.0:
@@ -478,7 +478,7 @@ class MSVCCompiler(CCompiler):
                 obj_names.append(os.path.join(output_dir, base + self.obj_extension))
         return obj_names
 
-    def compile(
+    def compile(  # noqa: C901
         self,
         sources,
         output_dir=None,
@@ -591,7 +591,7 @@ class MSVCCompiler(CCompiler):
         else:
             log.debug("skipping %s (up-to-date)", output_filename)
 
-    def link(
+    def link(  # noqa: C901
         self,
         target_desc,
         objects,
index 00c630be5092469c01bac86a2a6a1e05515fcc62..8e509ac50cd3317ab3d95960a444ba70c0297bc4 100644 (file)
@@ -8,7 +8,8 @@ for the Microsoft Visual Studio.
 # hacked by Robin Becker and Thomas Heller to do a better job of
 #   finding DevStudio (through the registry)
 
-import sys, os
+import sys
+import os
 from distutils.errors import (
     DistutilsExecError,
     DistutilsPlatformError,
@@ -134,7 +135,7 @@ class MacroExpander:
                 self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
             else:
                 self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
-        except KeyError as exc:  #
+        except KeyError:
             raise DistutilsPlatformError(
                 """Python was built with Visual Studio 2003;
 extensions must be built with a compiler than can generate compatible binaries.
@@ -368,7 +369,7 @@ class MSVCCompiler(CCompiler):
                 obj_names.append(os.path.join(output_dir, base + self.obj_extension))
         return obj_names
 
-    def compile(
+    def compile(  # noqa: C901
         self,
         sources,
         output_dir=None,
@@ -481,7 +482,7 @@ class MSVCCompiler(CCompiler):
         else:
             log.debug("skipping %s (up-to-date)", output_filename)
 
-    def link(
+    def link(  # noqa: C901
         self,
         target_desc,
         objects,
@@ -680,4 +681,4 @@ if get_build_version() >= 8.0:
     from distutils.msvc9compiler import MSVCCompiler
 
     # get_build_architecture not really relevant now we support cross-compile
-    from distutils.msvc9compiler import MacroExpander
+    from distutils.msvc9compiler import MacroExpander  # noqa: F811
index acd20148c7e6f8a81fbf1dfdea0feadf6bc6160f..db9f08ee6be49fdffdaa409b5bd5b17c3e068d86 100644 (file)
@@ -15,7 +15,7 @@ from distutils.debug import DEBUG
 from distutils import log
 
 
-def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):
+def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):  # noqa: C901
     """Run another program, specified as a command list 'cmd', in a new process.
 
     'cmd' is just the argument list for the new process, ie.
index e41d51ee55b3f11bc39687336f935aeafaab02ef..aae9c1b320aa5cf5b95ef0fa9c46e43b6e84561f 100644 (file)
@@ -250,7 +250,7 @@ def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
         )
 
 
-def customize_compiler(compiler):
+def customize_compiler(compiler):  # noqa: C901
     """Do any platform-specific customization of a CCompiler instance.
 
     Mainly needed on Unix, so we can plug in the information that
@@ -376,7 +376,7 @@ _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
 _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
 
 
-def parse_makefile(fn, g=None):
+def parse_makefile(fn, g=None):  # noqa: C901
     """Parse a Makefile-style file.
 
     A dictionary containing name/value pairs is returned.  If an
index c7dcc7ec3d45d126631a8a54a9010a883233c7d9..27e73393a0a52491d566d10ef1299669928f3ef7 100644 (file)
@@ -1,42 +1,8 @@
-"""Test suite for distutils.
-
-This test suite consists of a collection of test modules in the
-distutils.tests package.  Each test module has a name starting with
-'test' and contains a function test_suite().  The function is expected
-to return an initialized unittest.TestSuite instance.
+"""
+Test suite for distutils.
 
 Tests for the command classes in the distutils.command package are
 included in distutils.tests as well, instead of using a separate
 distutils.command.tests package, since command identification is done
 by import rather than matching pre-defined names.
-
 """
-
-import os
-import sys
-import unittest
-from test.support import run_unittest
-
-from .py38compat import save_restore_warnings_filters
-
-
-here = os.path.dirname(__file__) or os.curdir
-
-
-def test_suite():
-    suite = unittest.TestSuite()
-    for fn in os.listdir(here):
-        if fn.startswith("test") and fn.endswith(".py"):
-            modname = "distutils.tests." + fn[:-3]
-            # bpo-40055: Save/restore warnings filters to leave them unchanged.
-            # Importing tests imports docutils which imports pkg_resources
-            # which adds a warnings filter.
-            with save_restore_warnings_filters():
-                __import__(modname)
-            module = sys.modules[modname]
-            suite.addTest(module.test_suite())
-    return suite
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index c949f58ecde0180764322ab973922907dfd84e59..96f93a31c6250a928bbb7320857e097788fa736c 100644 (file)
@@ -42,21 +42,5 @@ except (ModuleNotFoundError, ImportError):
     )
 
 
-# From Python 3.9
-@contextlib.contextmanager
-def _save_restore_warnings_filters():
-    old_filters = warnings.filters[:]
-    try:
-        yield
-    finally:
-        warnings.filters[:] = old_filters
-
-
-try:
-    from test.support.warnings_helper import save_restore_warnings_filters
-except (ModuleNotFoundError, ImportError):
-    save_restore_warnings_filters = _save_restore_warnings_filters
-
-
 if sys.version_info < (3, 9):
     requires_zlib = lambda: test.support.requires_zlib
index 3085468a214ff3c4e68dc91c982b86831e5a13e5..2e9d66b7cf041d08ce0ec157d318505586026a99 100644 (file)
@@ -5,7 +5,6 @@ import shutil
 import tempfile
 import unittest
 import sysconfig
-from copy import deepcopy
 
 from . import py38compat as os_helper
 
@@ -116,23 +115,6 @@ class DummyCommand:
         pass
 
 
-class EnvironGuard(object):
-    def setUp(self):
-        super(EnvironGuard, self).setUp()
-        self.old_environ = deepcopy(os.environ)
-
-    def tearDown(self):
-        for key, value in self.old_environ.items():
-            if os.environ.get(key) != value:
-                os.environ[key] = value
-
-        for key in tuple(os.environ.keys()):
-            if key not in self.old_environ:
-                del os.environ[key]
-
-        super(EnvironGuard, self).tearDown()
-
-
 def copy_xxmodule_c(directory):
     """Helper for tests that need the xxmodule.c source file.
 
index 8fb95744223bc0e60988e219ed6d858fdced9307..7a324c4588e47c620cf53c726859ad6a95a90f2c 100644 (file)
@@ -7,6 +7,8 @@ import tarfile
 from os.path import splitdrive
 import warnings
 
+import pytest
+
 from distutils import archive_util
 from distutils.archive_util import (
     check_archive_formats,
@@ -17,7 +19,7 @@ from distutils.archive_util import (
 )
 from distutils.spawn import find_executable, spawn
 from distutils.tests import support
-from test.support import run_unittest, patch
+from test.support import patch
 from .unix_compat import require_unix_id, require_uid_0, grp, pwd, UID_0_SUPPORT
 
 from .py38compat import change_cwd
@@ -31,13 +33,6 @@ try:
 except ImportError:
     ZIP_SUPPORT = find_executable('zip')
 
-try:
-    import zlib
-
-    ZLIB_SUPPORT = True
-except ImportError:
-    ZLIB_SUPPORT = False
-
 try:
     import bz2
 except ImportError:
@@ -65,7 +60,7 @@ def can_fs_encode(filename):
 class ArchiveUtilTestCase(
     support.TempdirManager, support.LoggingSilencer, unittest.TestCase
 ):
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_make_tarball(self, name='archive'):
         # creating something to tar
         tmpdir = self._create_files()
@@ -73,7 +68,7 @@ class ArchiveUtilTestCase(
         # trying an uncompressed one
         self._make_tarball(tmpdir, name, '.tar', compress=None)
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_make_tarball_gzip(self):
         tmpdir = self._create_files()
         self._make_tarball(tmpdir, 'archive', '.tar.gz', compress='gzip')
@@ -156,9 +151,10 @@ class ArchiveUtilTestCase(
         os.mkdir(os.path.join(dist, 'sub2'))
         return tmpdir
 
+    @pytest.mark.usefixtures('needs_zlib')
     @unittest.skipUnless(
-        find_executable('tar') and find_executable('gzip') and ZLIB_SUPPORT,
-        'Need the tar, gzip and zlib command to run',
+        find_executable('tar') and find_executable('gzip'),
+        'Need the tar and gzip commands to run',
     )
     def test_tarfile_vs_tar(self):
         tmpdir = self._create_files()
@@ -247,9 +243,8 @@ class ArchiveUtilTestCase(
         self.assertFalse(os.path.exists(tarball))
         self.assertEqual(len(w.warnings), 1)
 
-    @unittest.skipUnless(
-        ZIP_SUPPORT and ZLIB_SUPPORT, 'Need zip and zlib support to run'
-    )
+    @pytest.mark.usefixtures('needs_zlib')
+    @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
     def test_make_zipfile(self):
         # creating something to tar
         tmpdir = self._create_files()
@@ -312,7 +307,7 @@ class ArchiveUtilTestCase(
         try:
             try:
                 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
-            except:
+            except Exception:
                 pass
             self.assertEqual(os.getcwd(), current_dir)
         finally:
@@ -326,7 +321,7 @@ class ArchiveUtilTestCase(
         self.assertEqual(os.path.basename(res), 'archive.tar')
         self.assertEqual(self._tarinfo(res), self._created_files)
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_make_archive_gztar(self):
         base_dir = self._create_files()
         base_name = os.path.join(self.mkdtemp(), 'archive')
@@ -383,7 +378,7 @@ class ArchiveUtilTestCase(
         )
         self.assertTrue(os.path.exists(res))
 
-    @unittest.skipUnless(ZLIB_SUPPORT, "Requires zlib")
+    @pytest.mark.usefixtures('needs_zlib')
     @require_unix_id
     @require_uid_0
     def test_tarfile_root_owner(self):
@@ -411,11 +406,3 @@ class ArchiveUtilTestCase(
                 self.assertEqual(member.gid, 0)
         finally:
             archive.close()
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(ArchiveUtilTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 2d0bb95b6f04990fac208cafc33bbd19cde735bc..8dbb829b6d618541a18f5394078158cd102fc58a 100644 (file)
@@ -1,7 +1,6 @@
 """Tests for distutils.command.bdist."""
 import os
 import unittest
-from test.support import run_unittest
 import warnings
 
 from distutils.command.bdist import bdist
@@ -30,7 +29,7 @@ class BuildTestCase(support.TempdirManager, unittest.TestCase):
             'zip',
             'ztar',
         ]
-        found = sorted(cmd.format_command)
+        found = sorted(cmd.format_commands)
         self.assertEqual(found, formats)
 
     def test_skip_build(self):
@@ -60,11 +59,3 @@ class BuildTestCase(support.TempdirManager, unittest.TestCase):
             self.assertTrue(
                 subcmd.skip_build, '%s should take --skip-build from bdist' % name
             )
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildTestCase)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index 83ab217d9e610ce7b440091c9fc5d0e4455a163d..7c4d5964ca59f8a9f94299f094932716f7cfbd51 100644 (file)
@@ -4,7 +4,8 @@ import os
 import sys
 import zipfile
 import unittest
-from test.support import run_unittest
+
+import pytest
 
 from distutils.core import Distribution
 from distutils.command.bdist_dumb import bdist_dumb
@@ -19,18 +20,11 @@ setup(name='foo', version='0.1', py_modules=['foo'],
 
 """
 
-try:
-    import zlib
-
-    ZLIB_SUPPORT = True
-except ImportError:
-    ZLIB_SUPPORT = False
-
 
+@pytest.mark.usefixtures('save_env')
 class BuildDumbTestCase(
     support.TempdirManager,
     support.LoggingSilencer,
-    support.EnvironGuard,
     unittest.TestCase,
 ):
     def setUp(self):
@@ -44,7 +38,7 @@ class BuildDumbTestCase(
         sys.argv[:] = self.old_sys_argv[1]
         super(BuildDumbTestCase, self).tearDown()
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_simple_built(self):
 
         # let's create a simple package
@@ -97,11 +91,3 @@ class BuildDumbTestCase(
         if not sys.dont_write_bytecode:
             wanted.append('foo.%s.pyc' % sys.implementation.cache_tag)
         self.assertEqual(contents, sorted(wanted))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildDumbTestCase)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index a9f3dbb59427ff05612579499c71700b5c901da0..3bfb7df1872381baac417b6dab62fbf7c1a7734d 100644 (file)
@@ -1,7 +1,6 @@
 """Tests for distutils.command.bdist_msi."""
 import sys
 import unittest
-from test.support import run_unittest
 from distutils.tests import support
 
 from .py38compat import check_warnings
@@ -19,11 +18,3 @@ class BDistMSITestCase(
         with check_warnings(("", DeprecationWarning)):
             cmd = bdist_msi(dist)
         cmd.ensure_finalized()
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BDistMSITestCase)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index f60a582a98215ac269a0dd7777037877da89da13..ba809392b04acd8c69b86d7a2a7bf396f7b0b3e1 100644 (file)
@@ -3,7 +3,8 @@
 import unittest
 import sys
 import os
-from test.support import run_unittest
+
+import pytest
 
 from distutils.core import Distribution
 from distutils.command.bdist_rpm import bdist_rpm
@@ -23,9 +24,9 @@ setup(name='foo', version='0.1', py_modules=['foo'],
 """
 
 
+@pytest.mark.usefixtures('save_env')
 class BuildRpmTestCase(
     support.TempdirManager,
-    support.EnvironGuard,
     support.LoggingSilencer,
     unittest.TestCase,
 ):
@@ -150,11 +151,3 @@ class BuildRpmTestCase(
         )
 
         os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm'))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildRpmTestCase)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index c103a63ba7a3d8ac8cf76daa8142d057a6a980f0..4e4fcc5b76ffb89d2342dbfaf146bfbc028981f6 100644 (file)
@@ -2,7 +2,6 @@
 import sys
 import platform
 import unittest
-from test.support import run_unittest
 
 from .py38compat import check_warnings
 
@@ -36,11 +35,3 @@ class BuildWinInstTestCase(
         # no matter what platform we have
         exe_file = cmd.get_exe_bytes()
         self.assertGreater(len(exe_file), 10)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildWinInstTestCase)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index 190bbdfdd6209da2cb6117106fa758e6949fba54..712b0d53293fb1a483a022608721b86e2f186e79 100644 (file)
@@ -2,7 +2,6 @@
 import unittest
 import os
 import sys
-from test.support import run_unittest
 
 from distutils.command.build import build
 from distutils.tests import support
@@ -45,11 +44,3 @@ class BuildTestCase(support.TempdirManager, support.LoggingSilencer, unittest.Te
 
         # executable is os.path.normpath(sys.executable)
         self.assertEqual(cmd.executable, os.path.normpath(sys.executable))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 24c7478753139f1812ad8d2ae863347ec2953b3e..c8fbb5c263945a6ebc182315cb1783dfb3e5d3d2 100644 (file)
@@ -3,7 +3,7 @@ import unittest
 import os
 import sys
 
-from test.support import run_unittest, missing_compiler_executable
+from test.support import missing_compiler_executable
 
 from distutils.command.build_clib import build_clib
 from distutils.errors import DistutilsSetupError
@@ -134,11 +134,3 @@ class BuildCLibTestCase(
 
         # let's check the result
         self.assertIn('libfoo.a', os.listdir(build_temp))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildCLibTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index c42ceabd957f456234fafb1019f458b90f7976a7..39d7920a5d4744e06f4b3c6411033c5f27cc9d11 100644 (file)
@@ -270,7 +270,7 @@ class BuildExtTestCase(TempdirManager, LoggingSilencer, unittest.TestCase):
         cmd = self.build_ext(dist)
         cmd.finalize_options()
 
-        #'extensions' option must be a list of Extension instances
+        # 'extensions' option must be a list of Extension instances
         self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, 'foo')
 
         # each element of 'ext_modules' option must be an
@@ -559,14 +559,3 @@ class ParallelBuildExtTestCase(BuildExtTestCase):
         build_ext = super().build_ext(*args, **kwargs)
         build_ext.parallel = True
         return build_ext
-
-
-def test_suite():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(BuildExtTestCase))
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ParallelBuildExtTestCase))
-    return suite
-
-
-if __name__ == '__main__':
-    support.run_unittest(__name__)
index eb01d81aea3bddb85a25de3de872f02db5fa23b1..4a8582e4b7e4a91bb66f62dce8f9753691299628 100644 (file)
@@ -10,7 +10,6 @@ from distutils.errors import DistutilsFileError
 from unittest.mock import patch
 
 from distutils.tests import support
-from test.support import run_unittest
 
 
 class BuildPyTestCase(
@@ -208,11 +207,3 @@ class BuildPyTestCase(
 
         cmd.run()
         # Test should complete successfully with no exception
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildPyTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 8c7061d7a20b469c7f8ba2e4977408ac0da7d5ac..6ef9dd618893076e6d54d5284a20764e651df75f 100644 (file)
@@ -8,7 +8,6 @@ from distutils.core import Distribution
 from distutils import sysconfig
 
 from distutils.tests import support
-from test.support import run_unittest
 
 
 class BuildScriptsTestCase(
@@ -108,11 +107,3 @@ class BuildScriptsTestCase(
         built = os.listdir(target)
         for name in expected:
             self.assertIn(name, built)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(BuildScriptsTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 424c5e08e50d3542191618178285d44383caecab..21035f5d4e5ac447fbf71b403f03204862af166a 100644 (file)
@@ -2,7 +2,6 @@
 import os
 import textwrap
 import unittest
-from test.support import run_unittest
 
 from distutils.command.check import check, HAS_DOCUTILS
 from distutils.tests import support
@@ -194,16 +193,6 @@ class CheckTestCase(support.LoggingSilencer, support.TempdirManager, unittest.Te
                 )
 
     def test_check_all(self):
-
-        metadata = {'url': 'xxx', 'author': 'xxx'}
         self.assertRaises(
             DistutilsSetupError, self._run, {}, **{'strict': 1, 'restructuredtext': 1}
         )
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(CheckTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 92e58f78a1eac3a7e8a8174750f4c942735de2ca..796ca0fca69d435e623d63b08c8985247c0aa1f8 100644 (file)
@@ -4,7 +4,6 @@ import unittest
 
 from distutils.command.clean import clean
 from distutils.tests import support
-from test.support import run_unittest
 
 
 class cleanTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase):
@@ -45,11 +44,3 @@ class cleanTestCase(support.TempdirManager, support.LoggingSilencer, unittest.Te
         cmd.all = 1
         cmd.ensure_finalized()
         cmd.run()
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(cleanTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 12a8a20c68cf4452356440755115a836a07ee55e..6a771a1106a3881d788a18e75d8bf2a34df6a0ed 100644 (file)
@@ -1,7 +1,7 @@
 """Tests for distutils.cmd."""
 import unittest
 import os
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
 
 from distutils.cmd import Command
 from distutils.dist import Distribution
@@ -122,11 +122,3 @@ class CommandTestCase(unittest.TestCase):
             self.assertEqual(stdout.read(), 'xxx\n')
         finally:
             debug.DEBUG = False
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(CommandTestCase)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index a4b4850969c1f9804e8366be7ce3bc3b2ac69328..5bca4da83a90a8e31de3323a302559116e016815 100644 (file)
@@ -2,13 +2,14 @@
 import os
 import unittest
 
+import pytest
+
 from distutils.core import PyPIRCCommand
 from distutils.core import Distribution
 from distutils.log import set_threshold
 from distutils.log import WARN
 
 from distutils.tests import support
-from test.support import run_unittest
 
 PYPIRC = """\
 [distutils]
@@ -50,10 +51,10 @@ password:xxx
 """
 
 
+@pytest.mark.usefixtures('save_env')
 class BasePyPIRCCommandTestCase(
     support.TempdirManager,
     support.LoggingSilencer,
-    support.EnvironGuard,
     unittest.TestCase,
 ):
     def setUp(self):
@@ -146,11 +147,3 @@ class PyPIRCCommandTestCase(BasePyPIRCCommandTestCase):
             ('username', 'cbiggles'),
         ]
         self.assertEqual(config, waited)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(PyPIRCCommandTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 0c1a9d253bf294a7321c5c67ffd6135a2a44242b..3c0879b59f9910b7e21eb983a2fcabd2aaceaa36 100644 (file)
@@ -2,7 +2,7 @@
 import unittest
 import os
 import sys
-from test.support import run_unittest, missing_compiler_executable
+from test.support import missing_compiler_executable
 
 from distutils.command.config import dump_file, config
 from distutils.tests import support
@@ -90,11 +90,3 @@ class ConfigTestCase(
 
         for f in (f1, f2):
             self.assertFalse(os.path.exists(f))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(ConfigTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 23402fb88fb5f1d7952eaf5b965c067c0a9c2d36..c3943866b9fc412a205edcd6f079c529b55872f9 100644 (file)
@@ -5,10 +5,12 @@ import distutils.core
 import os
 import shutil
 import sys
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
+
+import pytest
+
 from . import py38compat as os_helper
 import unittest
-from distutils.tests import support
 from distutils import log
 from distutils.dist import Distribution
 
@@ -57,7 +59,8 @@ if __name__ == "__main__":
 """
 
 
-class CoreTestCase(support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class CoreTestCase(unittest.TestCase):
     def setUp(self):
         super(CoreTestCase, self).setUp()
         self.old_stdout = sys.stdout
@@ -155,11 +158,3 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
         stdout.seek(0)
         wanted = "options (after parsing config files):\n"
         self.assertEqual(stdout.readlines()[0], wanted)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(CoreTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 7760436a6df71ad19729fa46b1ac2ec5f73f42b2..da73adc65aa47eabdf98c62323098d58cf262a21 100644 (file)
@@ -2,7 +2,6 @@
 import unittest
 import sys
 import os
-from test.support import run_unittest
 
 from distutils.cygwinccompiler import (
     check_config_h,
@@ -51,6 +50,7 @@ class CygwinCCompilerTestCase(support.TempdirManager, unittest.TestCase):
     @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'), [])
 
@@ -112,7 +112,10 @@ class CygwinCCompilerTestCase(support.TempdirManager, unittest.TestCase):
         )
         self.assertEqual(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)]'
+        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'])
 
         # unknown
@@ -120,11 +123,3 @@ class CygwinCCompilerTestCase(support.TempdirManager, unittest.TestCase):
             '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.2000 32 bits (Intel)]'
         )
         self.assertRaises(ValueError, get_msvcr)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(CygwinCCompilerTestCase)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index 89ae05d1778f41a11d78ca279eea3c25d4ec4f16..fb170c6f45eea9dfe22907ce7bdb137141bb7f00 100644 (file)
@@ -5,7 +5,6 @@ import os
 from distutils.dep_util import newer, newer_pairwise, newer_group
 from distutils.errors import DistutilsFileError
 from distutils.tests import support
-from test.support import run_unittest
 
 
 class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
@@ -68,11 +67,3 @@ class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
         self.assertFalse(newer_group([one, two, old_file], three, missing='ignore'))
 
         self.assertTrue(newer_group([one, two, old_file], three, missing='newer'))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(DepUtilTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index a1f9a240144e0fac13eecf4425efb7f81c787144..8231df695c98ba4cbc45d3df509188dc7c44c01f 100644 (file)
@@ -16,7 +16,6 @@ from distutils.dir_util import (
 
 from distutils import log
 from distutils.tests import support
-from test.support import run_unittest
 
 
 class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
@@ -134,11 +133,3 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
         ):
             src = self.tempdirs[-1]
             dir_util.copy_tree(src, None)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(DirUtilTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 6520a46d53a066dcb825d66c6290a962717988c7..59d165a44e2f6cfc52944407666ae2e3b53b51b9 100644 (file)
@@ -8,10 +8,12 @@ import textwrap
 
 from unittest import mock
 
+import pytest
+
 from distutils.dist import Distribution, fix_help_options
 from distutils.cmd import Command
 
-from test.support import captured_stdout, captured_stderr, run_unittest
+from test.support import captured_stdout, captured_stderr
 from .py38compat import TESTFN
 from distutils.tests import support
 from distutils import log
@@ -40,10 +42,10 @@ class TestDistribution(Distribution):
         return self._config_files
 
 
+@pytest.mark.usefixtures('save_env')
 class DistributionTestCase(
     support.LoggingSilencer,
     support.TempdirManager,
-    support.EnvironGuard,
     unittest.TestCase,
 ):
     def setUp(self):
@@ -121,7 +123,7 @@ class DistributionTestCase(
             )
 
         # Base case: Not in a Virtual Environment
-        with mock.patch.multiple(sys, prefix='/a', base_prefix='/a') as values:
+        with mock.patch.multiple(sys, prefix='/a', base_prefix='/a'):
             d = self.create_distribution([TESTFN])
 
         option_tuple = (TESTFN, fakepath)
@@ -150,7 +152,7 @@ class DistributionTestCase(
             self.assertEqual(value, result_dict[key])
 
         # Test case: In a Virtual Environment
-        with mock.patch.multiple(sys, prefix='/a', base_prefix='/b') as values:
+        with mock.patch.multiple(sys, prefix='/a', base_prefix='/b'):
             d = self.create_distribution([TESTFN])
 
         for key in result_dict.keys():
@@ -270,7 +272,8 @@ class DistributionTestCase(
         self.assertEqual(len(all_files) - 1, len(files))
 
 
-class MetadataTestCase(support.TempdirManager, support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class MetadataTestCase(support.TempdirManager, unittest.TestCase):
     def setUp(self):
         super(MetadataTestCase, self).setUp()
         self.argv = sys.argv, sys.argv[:]
@@ -552,14 +555,3 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, unittest.Te
         self.assertEqual(metadata.platforms, None)
         self.assertEqual(metadata.obsoletes, None)
         self.assertEqual(metadata.requires, ['foo'])
-
-
-def test_suite():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(DistributionTestCase))
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MetadataTestCase))
-    return suite
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 77fe3f82a6e538c025a5595e18359182400605be..bf5739304c7ce1ecb5ea0d53438299efbba11b91 100644 (file)
@@ -3,7 +3,6 @@ import unittest
 import os
 import warnings
 
-from test.support import run_unittest
 from distutils.extension import read_setup_file, Extension
 
 from .py38compat import check_warnings
@@ -102,11 +101,3 @@ class ExtensionTestCase(unittest.TestCase):
         self.assertEqual(
             str(w.warnings[0].message), "Unknown Extension options: 'chic'"
         )
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(ExtensionTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 22898b958074bf1bff0df58792bca5ff9281489b..6b333d5ea95d2d029a6f73507e8b374d5598dd41 100644 (file)
@@ -8,7 +8,6 @@ from distutils.file_util import move_file, copy_file
 from distutils import log
 from distutils.tests import support
 from distutils.errors import DistutilsFileError
-from test.support import run_unittest
 from .py38compat import unlink
 
 
@@ -115,11 +114,3 @@ class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
         for fn in (self.source, self.target):
             with open(fn, 'r') as f:
                 self.assertEqual(f.read(), 'some content')
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(FileUtilTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 71718a866fc2b3f0b21bda50329963758f3bccb2..0673139e6d93a7f10f7db571446dc275e08c6f87 100644 (file)
@@ -8,7 +8,7 @@ from distutils.errors import DistutilsTemplateError
 from distutils.filelist import glob_to_re, translate_pattern, FileList
 from distutils import filelist
 
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
 from distutils.tests import support
 
 from . import py38compat as os_helper
@@ -349,16 +349,3 @@ class FindAllTestCase(unittest.TestCase):
             os.symlink('.', link)
             files = filelist.findall(temp_dir)
             assert len(files) == 1
-
-
-def test_suite():
-    return unittest.TestSuite(
-        [
-            unittest.TestLoader().loadTestsFromTestCase(FileListTestCase),
-            unittest.TestLoader().loadTestsFromTestCase(FindAllTestCase),
-        ]
-    )
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 5f0a64dba11d0bd720909f2add66a3e0aaed4116..32ee02c74dcf33becc284a76276694d77a2e4f9a 100644 (file)
@@ -5,7 +5,9 @@ import sys
 import unittest
 import site
 
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
+
+import pytest
 
 from distutils import sysconfig
 from distutils.command.install import install
@@ -19,16 +21,14 @@ from distutils.extension import Extension
 from distutils.tests import support
 from test import support as test_support
 
-import pytest
-
 
 def _make_ext_name(modname):
     return modname + sysconfig.get_config_var('EXT_SUFFIX')
 
 
+@pytest.mark.usefixtures('save_env')
 class InstallTestCase(
     support.TempdirManager,
-    support.EnvironGuard,
     support.LoggingSilencer,
     unittest.TestCase,
 ):
@@ -272,11 +272,3 @@ class InstallTestCase(
         finally:
             install_module.DEBUG = False
         self.assertGreater(len(self.logs), old_logs_len)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(InstallTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index a08168b22e72ec74b28054e959482c0e7407388d..a66e5d406fad52b576411a33da7448c1a58ec725 100644 (file)
@@ -2,15 +2,16 @@
 import os
 import unittest
 
+import pytest
+
 from distutils.command.install_data import install_data
 from distutils.tests import support
-from test.support import run_unittest
 
 
+@pytest.mark.usefixtures('save_env')
 class InstallDataTestCase(
     support.TempdirManager,
     support.LoggingSilencer,
-    support.EnvironGuard,
     unittest.TestCase,
 ):
     def test_simple_run(self):
@@ -55,7 +56,6 @@ class InstallDataTestCase(
 
         # now using root and empty dir
         cmd.root = os.path.join(pkg_dir, 'root')
-        inst3 = os.path.join(cmd.install_dir, 'inst3')
         inst4 = os.path.join(pkg_dir, 'inst4')
         three = os.path.join(cmd.install_dir, 'three')
         self.write_file(three, 'xx')
@@ -67,11 +67,3 @@ class InstallDataTestCase(
         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)))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(InstallDataTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index db4f4dbb9e54e0dc7b161ba07dcc47d14a1e3a68..9029f7e45a6eda4f8234ae1ccf2d5b51dd6bb2b5 100644 (file)
@@ -2,15 +2,16 @@
 import os
 import unittest
 
+import pytest
+
 from distutils.command.install_headers import install_headers
 from distutils.tests import support
-from test.support import run_unittest
 
 
+@pytest.mark.usefixtures('save_env')
 class InstallHeadersTestCase(
     support.TempdirManager,
     support.LoggingSilencer,
-    support.EnvironGuard,
     unittest.TestCase,
 ):
     def test_simple_run(self):
@@ -33,11 +34,3 @@ class InstallHeadersTestCase(
 
         # let's check the results
         self.assertEqual(len(cmd.get_outputs()), 2)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(InstallHeadersTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 1ef233a7e922b7c55142e51534d92812203e1a7f..cebc88e74576b3b970d2ca624e781b6548fc1781 100644 (file)
@@ -4,17 +4,18 @@ import os
 import importlib.util
 import unittest
 
+import pytest
+
 from distutils.command.install_lib import install_lib
 from distutils.extension import Extension
 from distutils.tests import support
 from distutils.errors import DistutilsOptionError
-from test.support import run_unittest
 
 
+@pytest.mark.usefixtures('save_env')
 class InstallLibTestCase(
     support.TempdirManager,
     support.LoggingSilencer,
-    support.EnvironGuard,
     unittest.TestCase,
 ):
     def test_finalize_options(self):
@@ -107,11 +108,3 @@ class InstallLibTestCase(
             sys.dont_write_bytecode = old_dont_write_bytecode
 
         self.assertIn('byte-compiling is disabled', self.logs[0][1] % self.logs[0][2])
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(InstallLibTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index bac7880115e31a0b8dcefa030c821e938267f33c..2b19d7363097563b3b37f72b80dc2e6b394b362e 100644 (file)
@@ -7,7 +7,6 @@ from distutils.command.install_scripts import install_scripts
 from distutils.core import Distribution
 
 from distutils.tests import support
-from test.support import run_unittest
 
 
 class InstallScriptsTestCase(
@@ -77,11 +76,3 @@ class InstallScriptsTestCase(
         installed = os.listdir(target)
         for name in expected:
             self.assertIn(name, installed)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(InstallScriptsTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 33f7f96c34fc9ec6fd05df1ab9a5d98ada5b5c34..4a5c5a05c05c5b56fdde2e03ba600a7a59add0e0 100644 (file)
@@ -3,7 +3,7 @@
 import io
 import sys
 import unittest
-from test.support import swap_attr, run_unittest
+from test.support import swap_attr
 
 from distutils import log
 
@@ -51,11 +51,3 @@ class TestLog(unittest.TestCase):
                     if errors == 'ignore'
                     else 'Fαtal\t\\xc8rr\\u014dr',
                 )
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(TestLog)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index ec4781af1147d8b87a7dd6601f1df7a086b92f4e..11a45557ac6b2f859b7b75b72833cc4eaebe64c1 100644 (file)
@@ -5,7 +5,6 @@ import os
 
 from distutils.errors import DistutilsPlatformError
 from distutils.tests import support
-from test.support import run_unittest
 
 # A manifest with the only assembly reference being the msvcrt assembly, so
 # should have the assembly completely stripped.  Note that although the
@@ -182,11 +181,3 @@ class msvc9compilerTestCase(support.TempdirManager, unittest.TestCase):
         compiler = MSVCCompiler()
         got = compiler._remove_visual_c_ref(manifest)
         self.assertIsNone(got)
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(msvc9compilerTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 21fe57f8459d540cbaed0044452f8bb60327f03f..9357a22310ea44a3222475d8c2f72d041d489753 100644 (file)
@@ -4,19 +4,18 @@ import unittest
 import os
 import threading
 
+import pytest
+
 from distutils.errors import DistutilsPlatformError
 from distutils.tests import support
-from test.support import run_unittest
+from distutils import _msvccompiler
 
 
-SKIP_MESSAGE = None if sys.platform == "win32" else "These tests are only for win32"
+needs_winreg = pytest.mark.skipif('not hasattr(_msvccompiler, "winreg")')
 
 
-@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
 class msvccompilerTestCase(support.TempdirManager, unittest.TestCase):
     def test_no_compiler(self):
-        import distutils._msvccompiler as _msvccompiler
-
         # makes sure query_vcvarsall raises
         # a DistutilsPlatformError if the compiler
         # is not found
@@ -34,9 +33,8 @@ class msvccompilerTestCase(support.TempdirManager, unittest.TestCase):
         finally:
             _msvccompiler._find_vcvarsall = old_find_vcvarsall
 
+    @needs_winreg
     def test_get_vc_env_unicode(self):
-        import distutils._msvccompiler as _msvccompiler
-
         test_var = 'ṰḖṤṪ┅ṼẨṜ'
         test_value = '₃⁴₅'
 
@@ -52,9 +50,8 @@ class msvccompilerTestCase(support.TempdirManager, unittest.TestCase):
             if old_distutils_use_sdk:
                 os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk
 
+    @needs_winreg
     def test_get_vc2017(self):
-        import distutils._msvccompiler as _msvccompiler
-
         # This function cannot be mocked, so pass it if we find VS 2017
         # and mark it skipped if we do not.
         version, path = _msvccompiler._find_vc2017()
@@ -64,9 +61,8 @@ class msvccompilerTestCase(support.TempdirManager, unittest.TestCase):
         else:
             raise unittest.SkipTest("VS 2017 is not installed")
 
+    @needs_winreg
     def test_get_vc2015(self):
-        import distutils._msvccompiler as _msvccompiler
-
         # This function cannot be mocked, so pass it if we find VS 2015
         # and mark it skipped if we do not.
         version, path = _msvccompiler._find_vc2015()
@@ -95,8 +91,6 @@ class TestSpawn(unittest.TestCase):
         """
         Concurrent calls to spawn should have consistent results.
         """
-        import distutils._msvccompiler as _msvccompiler
-
         compiler = _msvccompiler.MSVCCompiler()
         compiler._paths = "expected"
         inner_cmd = 'import os; assert os.environ["PATH"] == "expected"'
@@ -116,7 +110,6 @@ class TestSpawn(unittest.TestCase):
         If CCompiler.spawn has been monkey-patched without support
         for an env, it should still execute.
         """
-        import distutils._msvccompiler as _msvccompiler
         from distutils import ccompiler
 
         compiler = _msvccompiler.MSVCCompiler()
@@ -130,11 +123,3 @@ class TestSpawn(unittest.TestCase):
             compiler.spawn(["n/a"])
 
         assert os.environ.get("PATH") != "expected"
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(msvccompilerTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 0f91ad3673516dcf21509ad558e2334671ae5a48..76fec6852166d1936eea45fdd059f52a564446ad 100644 (file)
@@ -5,7 +5,6 @@ import getpass
 import urllib
 import warnings
 
-from test.support import run_unittest
 
 from .py38compat import check_warnings
 
@@ -338,11 +337,3 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
 
         results = self.get_logs(INFO)
         self.assertEqual(results[3], 75 * '-' + '\nxxx\n' + 75 * '-')
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(RegisterTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 3a6aea237128048d03cffce8df15958e43c43476..f0ca829549639a0b16ef64dda58b093548a9636f 100644 (file)
@@ -6,17 +6,12 @@ import warnings
 import zipfile
 from os.path import join
 from textwrap import dedent
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
 from .unix_compat import require_unix_id, require_uid_0, pwd, grp
 
-from .py38compat import check_warnings
-
-try:
-    import zlib
+import pytest
 
-    ZLIB_SUPPORT = True
-except ImportError:
-    ZLIB_SUPPORT = False
+from .py38compat import check_warnings
 
 from distutils.command.sdist import sdist, show_formats
 from distutils.core import Distribution
@@ -88,7 +83,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
         cmd.dist_dir = 'dist'
         return dist, cmd
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_prune_file_list(self):
         # this test creates a project with some VCS dirs and an NFS rename
         # file, then launches sdist to check they get pruned on all systems
@@ -137,7 +132,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
         ]
         self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected])
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     @unittest.skipIf(find_executable('tar') is None, "The tar command is not found")
     @unittest.skipIf(find_executable('gzip') is None, "The gzip command is not found")
     def test_make_distribution(self):
@@ -168,7 +163,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
         result.sort()
         self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_add_defaults(self):
 
         # http://bugs.python.org/issue2279
@@ -258,7 +253,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
             f.close()
         self.assertEqual(manifest, MANIFEST % {'sep': os.sep})
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_metadata_check_option(self):
         # testing the `medata-check` option
         dist, cmd = self.get_cmd(metadata={})
@@ -350,7 +345,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
         # this used to crash instead of raising a warning: #8286
         self._check_template('include examples/')
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_get_file_list(self):
         # make sure MANIFEST is recalculated
         dist, cmd = self.get_cmd()
@@ -394,7 +389,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
         self.assertEqual(len(manifest2), 6)
         self.assertIn('doc2.txt', manifest2[-1])
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_manifest_marker(self):
         # check that autogenerated MANIFESTs have a marker
         dist, cmd = self.get_cmd()
@@ -411,7 +406,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
 
         self.assertEqual(manifest[0], '# file GENERATED by distutils, do NOT edit')
 
-    @unittest.skipUnless(ZLIB_SUPPORT, "Need zlib support to run")
+    @pytest.mark.usefixtures('needs_zlib')
     def test_manifest_comments(self):
         # make sure comments don't cause exceptions or wrong includes
         contents = dedent(
@@ -430,7 +425,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
         cmd.run()
         self.assertEqual(cmd.filelist.files, ['good.py'])
 
-    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+    @pytest.mark.usefixtures('needs_zlib')
     def test_manual_manifest(self):
         # check that a MANIFEST without a marker is left alone
         dist, cmd = self.get_cmd()
@@ -465,7 +460,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
             ['fake-1.0', 'fake-1.0/PKG-INFO', 'fake-1.0/README.manual'],
         )
 
-    @unittest.skipUnless(ZLIB_SUPPORT, "requires zlib")
+    @pytest.mark.usefixtures('needs_zlib')
     @require_unix_id
     @require_uid_0
     @unittest.skipIf(find_executable('tar') is None, "The tar command is not found")
@@ -511,11 +506,3 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
                 self.assertEqual(member.uid, os.getuid())
         finally:
             archive.close()
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(SDistTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index a773256287bf4c6f666ff8eb86a4b991860a9ee8..b86c157f8e9848bddde1006a3bb0104c2c5212b6 100644 (file)
@@ -3,7 +3,7 @@ import os
 import stat
 import sys
 import unittest.mock
-from test.support import run_unittest, unix_shell
+from test.support import unix_shell
 
 from . import py38compat as os_helper
 
@@ -123,11 +123,3 @@ class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.Te
         with self.assertRaises(DistutilsExecError) as ctx:
             spawn(['does-not-exist'])
         self.assertIn("command 'does-not-exist' failed", str(ctx.exception))
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(SpawnTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index a033e0750b7ae4ea032996d107383cd2ecd84136..2d68b5a3dea1ebaf02abb6107114b9fc318c3088 100644 (file)
@@ -7,19 +7,20 @@ import sys
 import textwrap
 import unittest
 
+import pytest
 import jaraco.envs
 
 import distutils
 from distutils import sysconfig
 from distutils.ccompiler import get_default_compiler
 from distutils.unixccompiler import UnixCCompiler
-from distutils.tests import support
-from test.support import run_unittest, swap_item
+from test.support import swap_item
 
 from .py38compat import TESTFN
 
 
-class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class SysconfigTestCase(unittest.TestCase):
     def setUp(self):
         super(SysconfigTestCase, self).setUp()
         self.makefile = None
@@ -331,13 +332,3 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
             cmd, env={**os.environ, "PYTHONPATH": distutils_path}
         )
         assert out == "True"
-
-
-def test_suite():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(SysconfigTestCase))
-    return suite
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index 16de9caae05c459d25afb8b222fe48ec4cb40543..ad10b6d50524d142f94316c19c6a3df8cfdc84ab 100644 (file)
@@ -3,7 +3,6 @@ import os
 import unittest
 from distutils.text_file import TextFile
 from distutils.tests import support
-from test.support import run_unittest
 
 TEST_DATA = """# test file
 
@@ -112,11 +111,3 @@ class TextFileTestCase(support.TempdirManager, unittest.TestCase):
             test_input(6, "join lines with collapsing", in_file, result6)
         finally:
             in_file.close()
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(TextFileTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index 879769fc8834e08eac83523cfcfcd6ba186459d6..3cd7c6caa70f21ce91c8e5b2f112b17e67f98a79 100644 (file)
@@ -2,7 +2,6 @@
 import os
 import sys
 import unittest
-from test.support import run_unittest
 from unittest.mock import patch
 
 from .py38compat import EnvironmentVarGuard
@@ -35,7 +34,7 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
         sysconfig.get_config_vars = self._backup_get_config_vars
 
     @unittest.skipIf(sys.platform == 'win32', "can't test on Windows")
-    def test_runtime_libdir_option(self):
+    def test_runtime_libdir_option(self):  # noqa: C901
         # Issue #5900; GitHub Issue #37
         #
         # Ensure RUNPATH is added to extension modules with RPATH if
@@ -307,11 +306,3 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
         self.cc.output_dir = 'scratch'
         os.chdir(self.mkdtemp())
         self.cc.has_function('abort', includes=['stdlib.h'])
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(UnixCCompilerTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index afba2faeddd2a624932c72167eee73b5649c10ae..a1d373064cbaca68858990bd021708bf93aa5b4c 100644 (file)
@@ -1,10 +1,8 @@
 """Tests for distutils.command.upload."""
 import os
-import unittest
 import unittest.mock as mock
 from urllib.request import HTTPError
 
-from test.support import run_unittest
 
 from distutils.command import upload as upload_mod
 from distutils.command.upload import upload
@@ -219,11 +217,3 @@ class uploadTestCase(BasePyPIRCCommandTestCase):
                     results = self.get_logs(ERROR)
                     self.assertIn(expected, results[-1])
                     self.clear_logs()
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(uploadTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index cebd61cca65e8c01c2c46ce2b808d007c3e06044..5a44f10a969794023b1d16c733fde0175fb20f24 100644 (file)
@@ -4,10 +4,10 @@ import sys
 import unittest
 import sysconfig as stdlib_sysconfig
 from copy import copy
-from test.support import run_unittest
 from unittest import mock
 
-from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
+import pytest
+
 from distutils.util import (
     get_platform,
     convert_path,
@@ -22,10 +22,11 @@ from distutils.util import (
 )
 from distutils import util  # used to patch _environ_checked
 from distutils import sysconfig
-from distutils.tests import support
+from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
 
 
-class UtilTestCase(support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class UtilTestCase(unittest.TestCase):
     def setUp(self):
         super(UtilTestCase, self).setUp()
         # saving the environment
@@ -237,11 +238,3 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
         exc = IOError("Unable to find batch file")
         msg = grok_environment_error(exc)
         self.assertEqual(msg, "error: Unable to find batch file")
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(UtilTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index cecb279f07b8ca43cc7a218ec6fedd0a26f18941..3727bac87d2aa6e8a19e4abfb8817e323691c44b 100644 (file)
@@ -3,7 +3,6 @@ import unittest
 import distutils
 from distutils.version import LooseVersion
 from distutils.version import StrictVersion
-from test.support import run_unittest
 
 
 class VersionTestCase(unittest.TestCase):
@@ -93,11 +92,3 @@ class VersionTestCase(unittest.TestCase):
                 NotImplemented,
                 'cmp(%s, %s) should be NotImplemented, got %s' % (v1, v2, res),
             )
-
-
-def test_suite():
-    return unittest.TestLoader().loadTestsFromTestCase(VersionTestCase)
-
-
-if __name__ == "__main__":
-    run_unittest(test_suite())
index ce3d0f46e05b703686e23302c6e267e87c47a5e7..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 (file)
@@ -1,15 +0,0 @@
-"""Tests harness for distutils.versionpredicate.
-
-"""
-
-import distutils.versionpredicate
-import doctest
-from test.support import run_unittest
-
-
-def test_suite():
-    return doctest.DocTestSuite(distutils.versionpredicate)
-
-
-if __name__ == '__main__':
-    run_unittest(test_suite())
index 015d68027cb328f73bdb3ace2e609e8d1c8094d8..cffcd0994cc36316a21e8171d332de3dca83fe8a 100644 (file)
@@ -4,7 +4,8 @@ provides the TextFile class, which gives an interface to text files
 that (optionally) takes care of stripping comments, ignoring blank
 lines, and joining lines with backslashes."""
 
-import sys, io
+import sys
+import io
 
 
 class TextFile:
@@ -152,7 +153,7 @@ class TextFile:
         line."""
         sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
 
-    def readline(self):
+    def readline(self):  # noqa: C901
         """Read and return a single logical line from the current file (or
         from an internal buffer if lines have previously been "unread"
         with 'unreadline()').  If the 'join_lines' option is true, this
index 4be74fdf3a0c1cde6fe2fab555302b49ed10b793..e4d930ac917bb7604523edd2cf038a2d38c32d3c 100644 (file)
@@ -13,7 +13,10 @@ the "typical" Unix-style command-line C compiler:
   * link shared library handled by 'cc -shared'
 """
 
-import os, sys, re, shlex
+import os
+import sys
+import re
+import shlex
 
 from distutils import sysconfig
 from distutils.dep_util import newer
@@ -160,17 +163,21 @@ class UnixCCompiler(CCompiler):
             pp_args.extend(extra_postargs)
         pp_args.append(source)
 
-        # We need to preprocess: either we're being forced to, or we're
-        # generating output to stdout, or there's a target output file and
-        # the source file is newer than the target (or the target doesn't
-        # exist).
-        if self.force or output_file is None or newer(source, output_file):
-            if output_file:
-                self.mkpath(os.path.dirname(output_file))
-            try:
-                self.spawn(pp_args)
-            except DistutilsExecError as msg:
-                raise CompileError(msg)
+        # reasons to preprocess:
+        # - force is indicated
+        # - output is directed to stdout
+        # - source file is newer than the target
+        preprocess = self.force or output_file is None or newer(source, output_file)
+        if not preprocess:
+            return
+
+        if output_file:
+            self.mkpath(os.path.dirname(output_file))
+
+        try:
+            self.spawn(pp_args)
+        except DistutilsExecError as msg:
+            raise CompileError(msg)
 
     def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
         compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
@@ -317,66 +324,60 @@ class UnixCCompiler(CCompiler):
     def library_option(self, lib):
         return "-l" + lib
 
-    def find_library_file(self, dirs, lib, debug=0):
-        shared_f = self.library_filename(lib, lib_type='shared')
-        dylib_f = self.library_filename(lib, lib_type='dylib')
-        xcode_stub_f = self.library_filename(lib, lib_type='xcode_stub')
-        static_f = self.library_filename(lib, lib_type='static')
-
-        if sys.platform == 'darwin':
-            # On OSX users can specify an alternate SDK using
-            # '-isysroot', calculate the SDK root if it is specified
-            # (and use it further on)
-            #
-            # Note that, as of Xcode 7, Apple SDKs may contain textual stub
-            # libraries with .tbd extensions rather than the normal .dylib
-            # shared libraries installed in /.  The Apple compiler tool
-            # chain handles this transparently but it can cause problems
-            # for programs that are being built with an SDK and searching
-            # for specific libraries.  Callers of find_library_file need to
-            # keep in mind that the base filename of the returned SDK library
-            # file might have a different extension from that of the library
-            # file installed on the running system, for example:
-            #   /Applications/Xcode.app/Contents/Developer/Platforms/
-            #       MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
-            #       usr/lib/libedit.tbd
-            # vs
-            #   /usr/lib/libedit.dylib
-            cflags = sysconfig.get_config_var('CFLAGS')
-            m = re.search(r'-isysroot\s*(\S+)', cflags)
-            if m is None:
-                sysroot = '/'
-            else:
-                sysroot = m.group(1)
-
-        for dir in dirs:
-            shared = os.path.join(dir, shared_f)
-            dylib = os.path.join(dir, dylib_f)
-            static = os.path.join(dir, static_f)
-            xcode_stub = os.path.join(dir, xcode_stub_f)
-
-            if sys.platform == 'darwin' and (
+    @staticmethod
+    def _library_root(dir):
+        """
+        macOS users can specify an alternate SDK using'-isysroot'.
+        Calculate the SDK root if it is specified.
+
+        Note that, as of Xcode 7, Apple SDKs may contain textual stub
+        libraries with .tbd extensions rather than the normal .dylib
+        shared libraries installed in /.  The Apple compiler tool
+        chain handles this transparently but it can cause problems
+        for programs that are being built with an SDK and searching
+        for specific libraries.  Callers of find_library_file need to
+        keep in mind that the base filename of the returned SDK library
+        file might have a different extension from that of the library
+        file installed on the running system, for example:
+          /Applications/Xcode.app/Contents/Developer/Platforms/
+              MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
+              usr/lib/libedit.tbd
+        vs
+          /usr/lib/libedit.dylib
+        """
+        cflags = sysconfig.get_config_var('CFLAGS')
+        match = re.search(r'-isysroot\s*(\S+)', cflags)
+
+        apply_root = (
+            sys.platform == 'darwin'
+            and match
+            and (
                 dir.startswith('/System/')
                 or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
-            ):
-
-                shared = os.path.join(sysroot, dir[1:], shared_f)
-                dylib = os.path.join(sysroot, dir[1:], dylib_f)
-                static = os.path.join(sysroot, dir[1:], static_f)
-                xcode_stub = os.path.join(sysroot, dir[1:], xcode_stub_f)
-
-            # We're second-guessing the linker here, with not much hard
-            # data to go on: GCC seems to prefer the shared library, so I'm
-            # assuming that *all* Unix C compilers do.  And of course I'm
-            # ignoring even GCC's "-static" option.  So sue me.
-            if os.path.exists(dylib):
-                return dylib
-            elif os.path.exists(xcode_stub):
-                return xcode_stub
-            elif os.path.exists(shared):
-                return shared
-            elif os.path.exists(static):
-                return static
-
-        # Oops, didn't find it in *any* of 'dirs'
-        return None
+            )
+        )
+
+        return os.path.join(match.group(1), dir[1:]) if apply_root else dir
+
+    def find_library_file(self, dirs, lib, debug=0):
+        """
+        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,
+        ignoring even GCC's "-static" option.
+        """
+        lib_names = (
+            self.library_filename(lib, lib_type=type)
+            for type in 'dylib xcode_stub shared static'.split()
+        )
+
+        searched = (
+            os.path.join(root, lib_name)
+            for root in map(self._library_root, dirs)
+            for lib_name in lib_names
+        )
+
+        found = filter(os.path.exists, searched)
+
+        # Return None if it could not be found in any dir.
+        return next(found, None)
index d59c362b86a7625aee2d0c975e438c0a02a0db6b..b22cf98486e8d3a951eeae17eb979db5038d1ad0 100644 (file)
@@ -11,11 +11,10 @@ import string
 import subprocess
 import sys
 import sysconfig
-from distutils.errors import DistutilsPlatformError
+from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
 from distutils.dep_util import newer
 from distutils.spawn import spawn
 from distutils import log
-from distutils.errors import DistutilsByteCompileError
 
 
 def get_host_platform():
@@ -360,7 +359,7 @@ def strtobool(val):
         raise ValueError("invalid truth value %r" % (val,))
 
 
-def byte_compile(
+def byte_compile(  # noqa: C901
     py_files,
     optimize=0,
     force=0,
index a406a301446b1c1079137f1834caa4448807a693..7e33fb7c9407f0e6f55dbd88d64f84574e3760e9 100644 (file)
@@ -180,7 +180,7 @@ class StrictVersion(Version):
 
         return vstring
 
-    def _cmp(self, other):
+    def _cmp(self, other):  # noqa: C901
         if isinstance(other, str):
             with suppress_known_deprecation():
                 other = StrictVersion(other)
index 5dc65e2d826ad94098cfec7a2c4550467c4dbfc1..a0d46a7989ad9a3e6fa45a3014d47f765ef357eb 100644 (file)
@@ -171,7 +171,7 @@ class _BuildMetaBackend:
         with _open_setup_script(__file__) as f:
             code = f.read().replace(r'\r\n', r'\n')
 
-        exec(compile(code, __file__, 'exec'), locals())
+        exec(code, locals())
 
     def get_requires_for_build_wheel(self, config_settings=None):
         return self._get_build_requires(
index b966dcea57a2072f98b96dbba75ceb26bd26d2dd..5acd7687d642f06de84b38f5842c41ae14d5f24a 100644 (file)
@@ -2,7 +2,11 @@ from distutils.command.bdist import bdist
 import sys
 
 if 'egg' not in bdist.format_commands:
-    bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
-    bdist.format_commands.append('egg')
+    try:
+        bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
+    except TypeError:
+        # For backward compatibility with older distutils (stdlib)
+        bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
+        bdist.format_commands.append('egg')
 
 del bdist, sys
index 35458d8e70a4d687064ade61404abeff20fb7a58..1a5153ad4fa51e14c83b8bb00345354d42ed3f0a 100644 (file)
@@ -25,7 +25,7 @@ def _deprecation_notice(fn: Fn) -> Fn:
         to access a backward compatible API, but this module is provisional
         and might be removed in the future.
         """
-        warnings.warn(dedent(msg), SetuptoolsDeprecationWarning)
+        warnings.warn(dedent(msg), SetuptoolsDeprecationWarning, stacklevel=2)
         return fn(*args, **kwargs)
 
     return cast(Fn, _wrapper)
index 9d11047bc5baea0419b5bad57a09ec754eab80f5..b44e32fcb8e5af484b51ea8eec7aea8099f90b7f 100644 (file)
@@ -27,7 +27,7 @@ from .helpers import Archive, run
 
 pytestmark = pytest.mark.integration
 
-LATEST, = list(Enum("v", "LATEST"))
+LATEST, = Enum("v", "LATEST")
 """Default version to be checked"""
 # There are positive and negative aspects of checking the latest version of the
 # packages.
@@ -72,11 +72,11 @@ VIRTUALENV = (sys.executable, "-m", "virtualenv")
 # means it will download the previous stable version of setuptools.
 # `pip` flags can avoid that (the version of setuptools under test
 # should be the one to be used)
-SDIST_OPTIONS = (
+INSTALL_OPTIONS = (
     "--ignore-installed",
     "--no-build-isolation",
-    # We don't need "--no-binary :all:" since we specify the path to the sdist.
-    # It also helps with performance, since dependencies can come from wheels.
+    # Omit "--no-binary :all:" the sdist is supplied directly.
+    # Allows dependencies as wheels.
 )
 # The downside of `--no-build-isolation` is that pip will not download build
 # dependencies. The test script will have to also handle that.
@@ -125,7 +125,7 @@ def test_install_sdist(package, version, tmp_path, venv_python, setuptools_wheel
     # Use a virtualenv to simulate PEP 517 isolation
     # but install fresh setuptools wheel to ensure the version under development
     run([*venv_pip, "install", "-I", setuptools_wheel])
-    run([*venv_pip, "install", *SDIST_OPTIONS, sdist])
+    run([*venv_pip, "install", *INSTALL_OPTIONS, sdist])
 
     # Execute a simple script to make sure the package was installed correctly
     script = f"import {package}; print(getattr({package}, '__version__', 0))"
@@ -165,17 +165,9 @@ def retrieve_pypi_sdist_metadata(package, version):
         raise ValueError(f"Release for {package} {version} was yanked")
 
     version = metadata["info"]["version"]
-    release = metadata["releases"][version]
-    dists = [d for d in release if d["packagetype"] == "sdist"]
-    if len(dists) == 0:
-        raise ValueError(f"No sdist found for {package} {version}")
-
-    for dist in dists:
-        if dist["filename"].endswith(".tar.gz"):
-            return dist
-
-    # Not all packages are publishing tar.gz
-    return dist
+    release = metadata["releases"][version] if version is LATEST else metadata["urls"]
+    sdist, = filter(lambda d: d["packagetype"] == "sdist", release)
+    return sdist
 
 
 def download(url, dest, md5_digest):
@@ -193,7 +185,7 @@ def download(url, dest, md5_digest):
 def build_deps(package, sdist_file):
     """Find out what are the build dependencies for a package.
 
-    We need to "manually" install them, since pip will not install build
+    "Manually" install them, since pip will not install build
     deps with `--no-build-isolation`.
     """
     import tomli as toml
@@ -202,9 +194,7 @@ def build_deps(package, sdist_file):
     # testenv without tomli
 
     archive = Archive(sdist_file)
-    pyproject = _read_pyproject(archive)
-
-    info = toml.loads(pyproject)
+    info = toml.loads(_read_pyproject(archive))
     deps = info.get("build-system", {}).get("requires", [])
     deps += EXTRA_BUILD_DEPS.get(package, [])
     # Remove setuptools from requirements (and deduplicate)
@@ -213,7 +203,9 @@ def build_deps(package, sdist_file):
 
 
 def _read_pyproject(archive):
-    for member in archive:
-        if os.path.basename(archive.get_name(member)) == "pyproject.toml":
-            return archive.get_content(member)
-    return ""
+    contents = (
+        archive.get_content(member)
+        for member in archive
+        if os.path.basename(archive.get_name(member)) == "pyproject.toml"
+    )
+    return next(contents, "")
index 8ac9bd072c05fd004581ea4847a291734a555a94..f8b82fcc37d6aa7ae49030296f6dd501a057948e 100644 (file)
@@ -107,9 +107,9 @@ class TestCLI(WrapperTester):
             'arg5 a\\\\b',
         ]
         proc = subprocess.Popen(
-            cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
-        stdout, stderr = proc.communicate('hello\nworld\n'.encode('ascii'))
-        actual = stdout.decode('ascii').replace('\r\n', '\n')
+            cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True)
+        stdout, stderr = proc.communicate('hello\nworld\n')
+        actual = stdout.replace('\r\n', '\n')
         expected = textwrap.dedent(r"""
             \foo-script.py
             ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b']
@@ -148,9 +148,11 @@ class TestCLI(WrapperTester):
             cmd,
             stdout=subprocess.PIPE,
             stdin=subprocess.PIPE,
-            stderr=subprocess.STDOUT)
+            stderr=subprocess.STDOUT,
+            text=True,
+        )
         stdout, stderr = proc.communicate()
-        actual = stdout.decode('ascii').replace('\r\n', '\n')
+        actual = stdout.replace('\r\n', '\n')
         expected = textwrap.dedent(r"""
             \foo-script.py
             []
@@ -188,7 +190,7 @@ class TestGUI(WrapperTester):
         ]
         proc = subprocess.Popen(
             cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
-            stderr=subprocess.STDOUT)
+            stderr=subprocess.STDOUT, text=True)
         stdout, stderr = proc.communicate()
         assert not stdout
         assert not stderr
diff --git a/tox.ini b/tox.ini
index bb2e7cb17d4e1910c651d9e84cfb2bcfa7635f23..13d944e5cc775b2e0d8f33fbc1bb2514945cddad 100644 (file)
--- a/tox.ini
+++ b/tox.ini
@@ -30,7 +30,7 @@ passenv =
 setenv =
     PROJECT_ROOT = {toxinidir}
 commands =
-       pytest --integration {posargs:-vv --durations=10 setuptools/tests/integration}
+       pytest --integration {posargs:-vv --durations=10} setuptools/tests/integration
        # use verbose mode by default to facilitate debugging from CI logs
 
 [testenv:docs]