From: JinWang An Date: Mon, 27 Mar 2023 08:02:52 +0000 (+0900) Subject: Imported Upstream version 63.3.0 X-Git-Tag: upstream/63.3.0^0 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=c59e1a4b5d02d32f9bc0a45ac5c88d1035efba03;p=platform%2Fupstream%2Fpython-setuptools.git Imported Upstream version 63.3.0 --- diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 284f7c1..24e18c3 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 63.1.0 +current_version = 63.3.0 commit = True tag = True diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7bd0af4..83624a5 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -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 diff --git a/CHANGES.rst b/CHANGES.rst index c85d6dc..48b5645 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -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 index 0000000..25f0b52 --- /dev/null +++ b/changelog.d/3475.change.rst @@ -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). diff --git a/docs/build_meta.rst b/docs/build_meta.rst index 45a994f..3c778d8 100644 --- a/docs/build_meta.rst +++ b/docs/build_meta.rst @@ -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"] diff --git a/docs/deprecated/commands.rst b/docs/deprecated/commands.rst index ebd0687..d9d97a9 100644 --- a/docs/deprecated/commands.rst +++ b/docs/deprecated/commands.rst @@ -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``):: diff --git a/docs/setuptools.rst b/docs/setuptools.rst index aa63830..5317058 100644 --- a/docs/setuptools.rst +++ b/docs/setuptools.rst @@ -151,7 +151,6 @@ To use this feature: [build-system] requires = [ "setuptools >= 40.9.0", - "wheel", ] build-backend = "setuptools.build_meta" diff --git a/docs/userguide/quickstart.rst b/docs/userguide/quickstart.rst index 6c39c35..060288d 100644 --- a/docs/userguide/quickstart.rst +++ b/docs/userguide/quickstart.rst @@ -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). diff --git a/pyproject.toml b/pyproject.toml index f6fdfc9..480b136 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,7 @@ addopts = "--flake8" [tool.pytest-enabler.cov] addopts = "--cov" -[pytest.enabler.xdist] +[tool.pytest-enabler.xdist] addopts = "-n auto" [tool.towncrier] diff --git a/setup.cfg b/setup.cfg index 65c8776..e99f12f 100644 --- 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" diff --git a/setuptools/_distutils/_msvccompiler.py b/setuptools/_distutils/_msvccompiler.py index 3b5a817..aa0cecc 100644 --- a/setuptools/_distutils/_msvccompiler.py +++ b/setuptools/_distutils/_msvccompiler.py @@ -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, diff --git a/setuptools/_distutils/archive_util.py b/setuptools/_distutils/archive_util.py index 5a70c32..4cb9bf3 100644 --- a/setuptools/_distutils/archive_util.py +++ b/setuptools/_distutils/archive_util.py @@ -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 diff --git a/setuptools/_distutils/bcppcompiler.py b/setuptools/_distutils/bcppcompiler.py index 056b2d9..7a6f951 100644 --- a/setuptools/_distutils/bcppcompiler.py +++ b/setuptools/_distutils/bcppcompiler.py @@ -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 diff --git a/setuptools/_distutils/ccompiler.py b/setuptools/_distutils/ccompiler.py index 005b64a..c1761d0 100644 --- a/setuptools/_distutils/ccompiler.py +++ b/setuptools/_distutils/ccompiler.py @@ -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") diff --git a/setuptools/_distutils/cmd.py b/setuptools/_distutils/cmd.py index 4a9bcc2..6f68801 100644 --- a/setuptools/_distutils/cmd.py +++ b/setuptools/_distutils/cmd.py @@ -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 diff --git a/setuptools/_distutils/command/__init__.py b/setuptools/_distutils/command/__init__.py index d199c24..a40c1f9 100644 --- a/setuptools/_distutils/command/__init__.py +++ b/setuptools/_distutils/command/__init__.py @@ -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 ] diff --git a/setuptools/_distutils/command/_framework_compat.py b/setuptools/_distutils/command/_framework_compat.py index e032603..cffa27c 100644 --- a/setuptools/_distutils/command/_framework_compat.py +++ b/setuptools/_distutils/command/_framework_compat.py @@ -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( diff --git a/setuptools/_distutils/command/bdist.py b/setuptools/_distutils/command/bdist.py index 2a63976..53f1321 100644 --- a/setuptools/_distutils/command/bdist.py +++ b/setuptools/_distutils/command/bdist.py @@ -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) diff --git a/setuptools/_distutils/command/bdist_dumb.py b/setuptools/_distutils/command/bdist_dumb.py index 3c38782..d3f519e 100644 --- a/setuptools/_distutils/command/bdist_dumb.py +++ b/setuptools/_distutils/command/bdist_dumb.py @@ -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 diff --git a/setuptools/_distutils/command/bdist_msi.py b/setuptools/_distutils/command/bdist_msi.py index 2f292c9..6e1e1ab 100644 --- a/setuptools/_distutils/command/bdist_msi.py +++ b/setuptools/_distutils/command/bdist_msi.py @@ -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") diff --git a/setuptools/_distutils/command/bdist_rpm.py b/setuptools/_distutils/command/bdist_rpm.py index cf4b952..fcfd7cd 100644 --- a/setuptools/_distutils/command/bdist_rpm.py +++ b/setuptools/_distutils/command/bdist_rpm.py @@ -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). """ diff --git a/setuptools/_distutils/command/bdist_wininst.py b/setuptools/_distutils/command/bdist_wininst.py index 76b8a89..7e9a64a 100644 --- a/setuptools/_distutils/command/bdist_wininst.py +++ b/setuptools/_distutils/command/bdist_wininst.py @@ -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 diff --git a/setuptools/_distutils/command/build.py b/setuptools/_distutils/command/build.py index 3aa7fac..e4b0642 100644 --- a/setuptools/_distutils/command/build.py +++ b/setuptools/_distutils/command/build.py @@ -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: diff --git a/setuptools/_distutils/command/build_clib.py b/setuptools/_distutils/command/build_clib.py index 003499f..50bb9bb 100644 --- a/setuptools/_distutils/command/build_clib.py +++ b/setuptools/_distutils/command/build_clib.py @@ -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 diff --git a/setuptools/_distutils/command/build_ext.py b/setuptools/_distutils/command/build_ext.py index 1a6dd39..153a0b6 100644 --- a/setuptools/_distutils/command/build_ext.py +++ b/setuptools/_distutils/command/build_ext.py @@ -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). diff --git a/setuptools/_distutils/command/build_py.py b/setuptools/_distutils/command/build_py.py index 7723d35..47c6158 100644 --- a/setuptools/_distutils/command/build_py.py +++ b/setuptools/_distutils/command/build_py.py @@ -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) diff --git a/setuptools/_distutils/command/build_scripts.py b/setuptools/_distutils/command/build_scripts.py index 17058db..2cc5d1e 100644 --- a/setuptools/_distutils/command/build_scripts.py +++ b/setuptools/_distutils/command/build_scripts.py @@ -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)) diff --git a/setuptools/_distutils/command/check.py b/setuptools/_distutils/command/check.py index 176a8b8..9c3523a 100644 --- a/setuptools/_distutils/command/check.py +++ b/setuptools/_distutils/command/check.py @@ -2,8 +2,6 @@ Implements the Distutils 'check' command. """ -from email.utils import getaddresses - from distutils.core import Command from distutils.errors import DistutilsSetupError diff --git a/setuptools/_distutils/command/config.py b/setuptools/_distutils/command/config.py index 73de1d3..4492c89 100644 --- a/setuptools/_distutils/command/config.py +++ b/setuptools/_distutils/command/config.py @@ -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 diff --git a/setuptools/_distutils/command/install.py b/setuptools/_distutils/command/install.py index 7d9054e..a38cddc 100644 --- a/setuptools/_distutils/command/install.py +++ b/setuptools/_distutils/command/install.py @@ -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 diff --git a/setuptools/_distutils/command/install_egg_info.py b/setuptools/_distutils/command/install_egg_info.py index dc93963..d5e68a6 100644 --- a/setuptools/_distutils/command/install_egg_info.py +++ b/setuptools/_distutils/command/install_egg_info.py @@ -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): diff --git a/setuptools/_distutils/command/register.py b/setuptools/_distutils/command/register.py index ca407eb..d2351ab 100644 --- a/setuptools/_distutils/command/register.py +++ b/setuptools/_distutils/command/register.py @@ -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( diff --git a/setuptools/_distutils/command/sdist.py b/setuptools/_distutils/command/sdist.py index aad3e71..ec3c97a 100644 --- a/setuptools/_distutils/command/sdist.py +++ b/setuptools/_distutils/command/sdist.py @@ -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(): diff --git a/setuptools/_distutils/command/upload.py b/setuptools/_distutils/command/upload.py index 782e3de..f2a8118 100644 --- a/setuptools/_distutils/command/upload.py +++ b/setuptools/_distutils/command/upload.py @@ -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: diff --git a/setuptools/_distutils/config.py b/setuptools/_distutils/config.py index 34a1c3b..6e0c3a7 100644 --- a/setuptools/_distutils/config.py +++ b/setuptools/_distutils/config.py @@ -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): diff --git a/setuptools/_distutils/core.py b/setuptools/_distutils/core.py index 305ecf6..333596a 100644 --- a/setuptools/_distutils/core.py +++ b/setuptools/_distutils/core.py @@ -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 diff --git a/setuptools/_distutils/cygwinccompiler.py b/setuptools/_distutils/cygwinccompiler.py index 445e2e5..e376446 100644 --- a/setuptools/_distutils/cygwinccompiler.py +++ b/setuptools/_distutils/cygwinccompiler.py @@ -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 diff --git a/setuptools/_distutils/dep_util.py b/setuptools/_distutils/dep_util.py index d94e111..db1fa01 100644 --- a/setuptools/_distutils/dep_util.py +++ b/setuptools/_distutils/dep_util.py @@ -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: diff --git a/setuptools/_distutils/dir_util.py b/setuptools/_distutils/dir_util.py index 2c19b98..7a132e3 100644 --- a/setuptools/_distutils/dir_util.py +++ b/setuptools/_distutils/dir_util.py @@ -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, diff --git a/setuptools/_distutils/dist.py b/setuptools/_distutils/dist.py index 82e3684..b4535eb 100644 --- a/setuptools/_distutils/dist.py +++ b/setuptools/_distutils/dist.py @@ -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'). diff --git a/setuptools/_distutils/extension.py b/setuptools/_distutils/extension.py index b05c5d9..dff2be9 100644 --- a/setuptools/_distutils/extension.py +++ b/setuptools/_distutils/extension.py @@ -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 diff --git a/setuptools/_distutils/fancy_getopt.py b/setuptools/_distutils/fancy_getopt.py index b9b2176..9ee0642 100644 --- a/setuptools/_distutils/fancy_getopt.py +++ b/setuptools/_distutils/fancy_getopt.py @@ -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] == ' ': diff --git a/setuptools/_distutils/file_util.py b/setuptools/_distutils/file_util.py index 4ff2230..0662fe4 100644 --- a/setuptools/_distutils/file_util.py +++ b/setuptools/_distutils/file_util.py @@ -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 diff --git a/setuptools/_distutils/filelist.py b/setuptools/_distutils/filelist.py index 37ab341..4396d9d 100644 --- a/setuptools/_distutils/filelist.py +++ b/setuptools/_distutils/filelist.py @@ -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 diff --git a/setuptools/_distutils/msvc9compiler.py b/setuptools/_distutils/msvc9compiler.py index 225f1a2..276e137 100644 --- a/setuptools/_distutils/msvc9compiler.py +++ b/setuptools/_distutils/msvc9compiler.py @@ -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, diff --git a/setuptools/_distutils/msvccompiler.py b/setuptools/_distutils/msvccompiler.py index 00c630b..8e509ac 100644 --- a/setuptools/_distutils/msvccompiler.py +++ b/setuptools/_distutils/msvccompiler.py @@ -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 diff --git a/setuptools/_distutils/spawn.py b/setuptools/_distutils/spawn.py index acd2014..db9f08e 100644 --- a/setuptools/_distutils/spawn.py +++ b/setuptools/_distutils/spawn.py @@ -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. diff --git a/setuptools/_distutils/sysconfig.py b/setuptools/_distutils/sysconfig.py index e41d51e..aae9c1b 100644 --- a/setuptools/_distutils/sysconfig.py +++ b/setuptools/_distutils/sysconfig.py @@ -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 diff --git a/setuptools/_distutils/tests/__init__.py b/setuptools/_distutils/tests/__init__.py index c7dcc7e..27e7339 100644 --- a/setuptools/_distutils/tests/__init__.py +++ b/setuptools/_distutils/tests/__init__.py @@ -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()) diff --git a/setuptools/_distutils/tests/py38compat.py b/setuptools/_distutils/tests/py38compat.py index c949f58..96f93a3 100644 --- a/setuptools/_distutils/tests/py38compat.py +++ b/setuptools/_distutils/tests/py38compat.py @@ -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 diff --git a/setuptools/_distutils/tests/support.py b/setuptools/_distutils/tests/support.py index 3085468..2e9d66b 100644 --- a/setuptools/_distutils/tests/support.py +++ b/setuptools/_distutils/tests/support.py @@ -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. diff --git a/setuptools/_distutils/tests/test_archive_util.py b/setuptools/_distutils/tests/test_archive_util.py index 8fb9574..7a324c4 100644 --- a/setuptools/_distutils/tests/test_archive_util.py +++ b/setuptools/_distutils/tests/test_archive_util.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_bdist.py b/setuptools/_distutils/tests/test_bdist.py index 2d0bb95..8dbb829 100644 --- a/setuptools/_distutils/tests/test_bdist.py +++ b/setuptools/_distutils/tests/test_bdist.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_bdist_dumb.py b/setuptools/_distutils/tests/test_bdist_dumb.py index 83ab217..7c4d596 100644 --- a/setuptools/_distutils/tests/test_bdist_dumb.py +++ b/setuptools/_distutils/tests/test_bdist_dumb.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_bdist_msi.py b/setuptools/_distutils/tests/test_bdist_msi.py index a9f3dbb..3bfb7df 100644 --- a/setuptools/_distutils/tests/test_bdist_msi.py +++ b/setuptools/_distutils/tests/test_bdist_msi.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_bdist_rpm.py b/setuptools/_distutils/tests/test_bdist_rpm.py index f60a582..ba80939 100644 --- a/setuptools/_distutils/tests/test_bdist_rpm.py +++ b/setuptools/_distutils/tests/test_bdist_rpm.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_bdist_wininst.py b/setuptools/_distutils/tests/test_bdist_wininst.py index c103a63..4e4fcc5 100644 --- a/setuptools/_distutils/tests/test_bdist_wininst.py +++ b/setuptools/_distutils/tests/test_bdist_wininst.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_build.py b/setuptools/_distutils/tests/test_build.py index 190bbdf..712b0d5 100644 --- a/setuptools/_distutils/tests/test_build.py +++ b/setuptools/_distutils/tests/test_build.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_build_clib.py b/setuptools/_distutils/tests/test_build_clib.py index 24c7478..c8fbb5c 100644 --- a/setuptools/_distutils/tests/test_build_clib.py +++ b/setuptools/_distutils/tests/test_build_clib.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_build_ext.py b/setuptools/_distutils/tests/test_build_ext.py index c42ceab..39d7920 100644 --- a/setuptools/_distutils/tests/test_build_ext.py +++ b/setuptools/_distutils/tests/test_build_ext.py @@ -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__) diff --git a/setuptools/_distutils/tests/test_build_py.py b/setuptools/_distutils/tests/test_build_py.py index eb01d81..4a8582e 100644 --- a/setuptools/_distutils/tests/test_build_py.py +++ b/setuptools/_distutils/tests/test_build_py.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_build_scripts.py b/setuptools/_distutils/tests/test_build_scripts.py index 8c7061d..6ef9dd6 100644 --- a/setuptools/_distutils/tests/test_build_scripts.py +++ b/setuptools/_distutils/tests/test_build_scripts.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_check.py b/setuptools/_distutils/tests/test_check.py index 424c5e0..21035f5 100644 --- a/setuptools/_distutils/tests/test_check.py +++ b/setuptools/_distutils/tests/test_check.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_clean.py b/setuptools/_distutils/tests/test_clean.py index 92e58f7..796ca0f 100644 --- a/setuptools/_distutils/tests/test_clean.py +++ b/setuptools/_distutils/tests/test_clean.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_cmd.py b/setuptools/_distutils/tests/test_cmd.py index 12a8a20..6a771a1 100644 --- a/setuptools/_distutils/tests/test_cmd.py +++ b/setuptools/_distutils/tests/test_cmd.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_config.py b/setuptools/_distutils/tests/test_config.py index a4b4850..5bca4da 100644 --- a/setuptools/_distutils/tests/test_config.py +++ b/setuptools/_distutils/tests/test_config.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_config_cmd.py b/setuptools/_distutils/tests/test_config_cmd.py index 0c1a9d2..3c0879b 100644 --- a/setuptools/_distutils/tests/test_config_cmd.py +++ b/setuptools/_distutils/tests/test_config_cmd.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_core.py b/setuptools/_distutils/tests/test_core.py index 23402fb..c394386 100644 --- a/setuptools/_distutils/tests/test_core.py +++ b/setuptools/_distutils/tests/test_core.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_cygwinccompiler.py b/setuptools/_distutils/tests/test_cygwinccompiler.py index 7760436..da73adc 100644 --- a/setuptools/_distutils/tests/test_cygwinccompiler.py +++ b/setuptools/_distutils/tests/test_cygwinccompiler.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_dep_util.py b/setuptools/_distutils/tests/test_dep_util.py index 89ae05d..fb170c6 100644 --- a/setuptools/_distutils/tests/test_dep_util.py +++ b/setuptools/_distutils/tests/test_dep_util.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_dir_util.py b/setuptools/_distutils/tests/test_dir_util.py index a1f9a24..8231df6 100644 --- a/setuptools/_distutils/tests/test_dir_util.py +++ b/setuptools/_distutils/tests/test_dir_util.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_dist.py b/setuptools/_distutils/tests/test_dist.py index 6520a46..59d165a 100644 --- a/setuptools/_distutils/tests/test_dist.py +++ b/setuptools/_distutils/tests/test_dist.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_extension.py b/setuptools/_distutils/tests/test_extension.py index 77fe3f8..bf57393 100644 --- a/setuptools/_distutils/tests/test_extension.py +++ b/setuptools/_distutils/tests/test_extension.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_file_util.py b/setuptools/_distutils/tests/test_file_util.py index 22898b9..6b333d5 100644 --- a/setuptools/_distutils/tests/test_file_util.py +++ b/setuptools/_distutils/tests/test_file_util.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_filelist.py b/setuptools/_distutils/tests/test_filelist.py index 71718a8..0673139 100644 --- a/setuptools/_distutils/tests/test_filelist.py +++ b/setuptools/_distutils/tests/test_filelist.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_install.py b/setuptools/_distutils/tests/test_install.py index 5f0a64d..32ee02c 100644 --- a/setuptools/_distutils/tests/test_install.py +++ b/setuptools/_distutils/tests/test_install.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_install_data.py b/setuptools/_distutils/tests/test_install_data.py index a08168b..a66e5d4 100644 --- a/setuptools/_distutils/tests/test_install_data.py +++ b/setuptools/_distutils/tests/test_install_data.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_install_headers.py b/setuptools/_distutils/tests/test_install_headers.py index db4f4db..9029f7e 100644 --- a/setuptools/_distutils/tests/test_install_headers.py +++ b/setuptools/_distutils/tests/test_install_headers.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_install_lib.py b/setuptools/_distutils/tests/test_install_lib.py index 1ef233a..cebc88e 100644 --- a/setuptools/_distutils/tests/test_install_lib.py +++ b/setuptools/_distutils/tests/test_install_lib.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_install_scripts.py b/setuptools/_distutils/tests/test_install_scripts.py index bac7880..2b19d73 100644 --- a/setuptools/_distutils/tests/test_install_scripts.py +++ b/setuptools/_distutils/tests/test_install_scripts.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_log.py b/setuptools/_distutils/tests/test_log.py index 33f7f96..4a5c5a0 100644 --- a/setuptools/_distutils/tests/test_log.py +++ b/setuptools/_distutils/tests/test_log.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_msvc9compiler.py b/setuptools/_distutils/tests/test_msvc9compiler.py index ec4781a..11a4555 100644 --- a/setuptools/_distutils/tests/test_msvc9compiler.py +++ b/setuptools/_distutils/tests/test_msvc9compiler.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_msvccompiler.py b/setuptools/_distutils/tests/test_msvccompiler.py index 21fe57f..9357a22 100644 --- a/setuptools/_distutils/tests/test_msvccompiler.py +++ b/setuptools/_distutils/tests/test_msvccompiler.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_register.py b/setuptools/_distutils/tests/test_register.py index 0f91ad3..76fec68 100644 --- a/setuptools/_distutils/tests/test_register.py +++ b/setuptools/_distutils/tests/test_register.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_sdist.py b/setuptools/_distutils/tests/test_sdist.py index 3a6aea2..f0ca829 100644 --- a/setuptools/_distutils/tests/test_sdist.py +++ b/setuptools/_distutils/tests/test_sdist.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_spawn.py b/setuptools/_distutils/tests/test_spawn.py index a773256..b86c157 100644 --- a/setuptools/_distutils/tests/test_spawn.py +++ b/setuptools/_distutils/tests/test_spawn.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_sysconfig.py b/setuptools/_distutils/tests/test_sysconfig.py index a033e07..2d68b5a 100644 --- a/setuptools/_distutils/tests/test_sysconfig.py +++ b/setuptools/_distutils/tests/test_sysconfig.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_text_file.py b/setuptools/_distutils/tests/test_text_file.py index 16de9ca..ad10b6d 100644 --- a/setuptools/_distutils/tests/test_text_file.py +++ b/setuptools/_distutils/tests/test_text_file.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_unixccompiler.py b/setuptools/_distutils/tests/test_unixccompiler.py index 879769f..3cd7c6c 100644 --- a/setuptools/_distutils/tests/test_unixccompiler.py +++ b/setuptools/_distutils/tests/test_unixccompiler.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_upload.py b/setuptools/_distutils/tests/test_upload.py index afba2fa..a1d3730 100644 --- a/setuptools/_distutils/tests/test_upload.py +++ b/setuptools/_distutils/tests/test_upload.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_util.py b/setuptools/_distutils/tests/test_util.py index cebd61c..5a44f10 100644 --- a/setuptools/_distutils/tests/test_util.py +++ b/setuptools/_distutils/tests/test_util.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_version.py b/setuptools/_distutils/tests/test_version.py index cecb279..3727bac 100644 --- a/setuptools/_distutils/tests/test_version.py +++ b/setuptools/_distutils/tests/test_version.py @@ -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()) diff --git a/setuptools/_distutils/tests/test_versionpredicate.py b/setuptools/_distutils/tests/test_versionpredicate.py index ce3d0f4..e69de29 100644 --- a/setuptools/_distutils/tests/test_versionpredicate.py +++ b/setuptools/_distutils/tests/test_versionpredicate.py @@ -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()) diff --git a/setuptools/_distutils/text_file.py b/setuptools/_distutils/text_file.py index 015d680..cffcd09 100644 --- a/setuptools/_distutils/text_file.py +++ b/setuptools/_distutils/text_file.py @@ -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 diff --git a/setuptools/_distutils/unixccompiler.py b/setuptools/_distutils/unixccompiler.py index 4be74fd..e4d930a 100644 --- a/setuptools/_distutils/unixccompiler.py +++ b/setuptools/_distutils/unixccompiler.py @@ -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) diff --git a/setuptools/_distutils/util.py b/setuptools/_distutils/util.py index d59c362..b22cf98 100644 --- a/setuptools/_distutils/util.py +++ b/setuptools/_distutils/util.py @@ -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, diff --git a/setuptools/_distutils/version.py b/setuptools/_distutils/version.py index a406a30..7e33fb7 100644 --- a/setuptools/_distutils/version.py +++ b/setuptools/_distutils/version.py @@ -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) diff --git a/setuptools/build_meta.py b/setuptools/build_meta.py index 5dc65e2..a0d46a7 100644 --- a/setuptools/build_meta.py +++ b/setuptools/build_meta.py @@ -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( diff --git a/setuptools/command/__init__.py b/setuptools/command/__init__.py index b966dce..5acd768 100644 --- a/setuptools/command/__init__.py +++ b/setuptools/command/__init__.py @@ -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 diff --git a/setuptools/config/__init__.py b/setuptools/config/__init__.py index 35458d8..1a5153a 100644 --- a/setuptools/config/__init__.py +++ b/setuptools/config/__init__.py @@ -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) diff --git a/setuptools/tests/integration/test_pip_install_sdist.py b/setuptools/tests/integration/test_pip_install_sdist.py index 9d11047..b44e32f 100644 --- a/setuptools/tests/integration/test_pip_install_sdist.py +++ b/setuptools/tests/integration/test_pip_install_sdist.py @@ -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, "") diff --git a/setuptools/tests/test_windows_wrappers.py b/setuptools/tests/test_windows_wrappers.py index 8ac9bd0..f8b82fc 100644 --- a/setuptools/tests/test_windows_wrappers.py +++ b/setuptools/tests/test_windows_wrappers.py @@ -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 bb2e7cb..13d944e 100644 --- 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]