diff options
author | Jason R. Coombs <jaraco@jaraco.com> | 2020-09-04 10:22:54 -0400 |
---|---|---|
committer | Jason R. Coombs <jaraco@jaraco.com> | 2020-09-04 10:22:54 -0400 |
commit | fc4d9828768ceebd2f9337481450c88376c013e9 (patch) | |
tree | 6dff622c50739ca19fdfbecf1008a42589d37b57 /setuptools/tests | |
parent | 7bb73a477de24069002516eb6eb1d755bed9d65b (diff) | |
parent | 03d36b9edb53e266a0b4b836e1e3178f989a0781 (diff) | |
download | python-setuptools-git-feature/implicit-bootstrap.tar.gz |
Merge branch 'master' into feature/implicit-bootstrapfeature/implicit-bootstrap
Diffstat (limited to 'setuptools/tests')
34 files changed, 483 insertions, 506 deletions
diff --git a/setuptools/tests/__init__.py b/setuptools/tests/__init__.py index 9c77b51f..a7a2112f 100644 --- a/setuptools/tests/__init__.py +++ b/setuptools/tests/__init__.py @@ -2,17 +2,12 @@ import locale import pytest -from setuptools.extern.six import PY2, PY3 - -__all__ = [ - 'fail_on_ascii', 'py2_only', 'py3_only' -] +__all__ = ['fail_on_ascii', 'ack_2to3'] is_ascii = locale.getpreferredencoding() == 'ANSI_X3.4-1968' fail_on_ascii = pytest.mark.xfail(is_ascii, reason="Test fails in this locale") -py2_only = pytest.mark.skipif(not PY2, reason="Test runs on Python 2 only") -py3_only = pytest.mark.skipif(not PY3, reason="Test runs on Python 3 only") +ack_2to3 = pytest.mark.filterwarnings('ignore:2to3 support is deprecated') diff --git a/setuptools/tests/contexts.py b/setuptools/tests/contexts.py index 535ae107..51ce8984 100644 --- a/setuptools/tests/contexts.py +++ b/setuptools/tests/contexts.py @@ -4,8 +4,8 @@ import shutil import sys import contextlib import site +import io -from setuptools.extern import six import pkg_resources @@ -58,8 +58,8 @@ def quiet(): old_stdout = sys.stdout old_stderr = sys.stderr - new_stdout = sys.stdout = six.StringIO() - new_stderr = sys.stderr = six.StringIO() + new_stdout = sys.stdout = io.StringIO() + new_stderr = sys.stderr = io.StringIO() try: yield new_stdout, new_stderr finally: diff --git a/setuptools/tests/files.py b/setuptools/tests/files.py index bad2189d..71194b9d 100644 --- a/setuptools/tests/files.py +++ b/setuptools/tests/files.py @@ -1,9 +1,6 @@ import os -import pkg_resources.py31compat - - def build_files(file_defs, prefix=""): """ Build a set of files/directories, as described by the @@ -30,7 +27,7 @@ def build_files(file_defs, prefix=""): for name, contents in file_defs.items(): full_name = os.path.join(prefix, name) if isinstance(contents, dict): - pkg_resources.py31compat.makedirs(full_name, exist_ok=True) + os.makedirs(full_name, exist_ok=True) build_files(contents, prefix=full_name) else: if isinstance(contents, bytes): diff --git a/setuptools/tests/namespaces.py b/setuptools/tests/namespaces.py index ef5ecdad..245cf8ea 100644 --- a/setuptools/tests/namespaces.py +++ b/setuptools/tests/namespaces.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, unicode_literals - import textwrap diff --git a/setuptools/tests/requirements.txt b/setuptools/tests/requirements.txt index 19bf5aef..d0d07f70 100644 --- a/setuptools/tests/requirements.txt +++ b/setuptools/tests/requirements.txt @@ -10,3 +10,4 @@ pytest-cov>=2.5.1 paver; python_version>="3.6" futures; python_version=="2.7" pip>=19.1 # For proper file:// URLs support. +jaraco.envs diff --git a/setuptools/tests/server.py b/setuptools/tests/server.py index 8b17b081..7e213230 100644 --- a/setuptools/tests/server.py +++ b/setuptools/tests/server.py @@ -4,13 +4,12 @@ import os import time import threading +import http.server +import urllib.parse +import urllib.request -from setuptools.extern.six.moves import BaseHTTPServer, SimpleHTTPServer -from setuptools.extern.six.moves.urllib_parse import urljoin -from setuptools.extern.six.moves.urllib.request import pathname2url - -class IndexServer(BaseHTTPServer.HTTPServer): +class IndexServer(http.server.HTTPServer): """Basic single-threaded http server simulating a package index You can use this server in unittest like this:: @@ -24,8 +23,8 @@ class IndexServer(BaseHTTPServer.HTTPServer): def __init__( self, server_address=('', 0), - RequestHandlerClass=SimpleHTTPServer.SimpleHTTPRequestHandler): - BaseHTTPServer.HTTPServer.__init__( + RequestHandlerClass=http.server.SimpleHTTPRequestHandler): + http.server.HTTPServer.__init__( self, server_address, RequestHandlerClass) self._run = True @@ -48,14 +47,14 @@ class IndexServer(BaseHTTPServer.HTTPServer): return 'http://127.0.0.1:%s/setuptools/tests/indexes/' % port -class RequestRecorder(BaseHTTPServer.BaseHTTPRequestHandler): +class RequestRecorder(http.server.BaseHTTPRequestHandler): def do_GET(self): requests = vars(self.server).setdefault('requests', []) requests.append(self) self.send_response(200, 'OK') -class MockServer(BaseHTTPServer.HTTPServer, threading.Thread): +class MockServer(http.server.HTTPServer, threading.Thread): """ A simple HTTP Server that records the requests made to it. """ @@ -63,7 +62,7 @@ class MockServer(BaseHTTPServer.HTTPServer, threading.Thread): def __init__( self, server_address=('', 0), RequestHandlerClass=RequestRecorder): - BaseHTTPServer.HTTPServer.__init__( + http.server.HTTPServer.__init__( self, server_address, RequestHandlerClass) threading.Thread.__init__(self) self.setDaemon(True) @@ -87,5 +86,5 @@ def path_to_url(path, authority=None): base = 'file:' if authority is not None: base += '//' + authority - url = urljoin(base, pathname2url(path)) + url = urllib.parse.urljoin(base, urllib.request.pathname2url(path)) return url diff --git a/setuptools/tests/test_archive_util.py b/setuptools/tests/test_archive_util.py index b789e9ac..7f996244 100644 --- a/setuptools/tests/test_archive_util.py +++ b/setuptools/tests/test_archive_util.py @@ -3,8 +3,6 @@ import tarfile import io -from setuptools.extern import six - import pytest from setuptools import archive_util @@ -22,8 +20,6 @@ def tarfile_with_unicode(tmpdir): data = b"" filename = "testimäge.png" - if six.PY2: - filename = filename.decode('utf-8') t = tarfile.TarInfo(filename) t.size = len(data) @@ -39,4 +35,4 @@ def tarfile_with_unicode(tmpdir): @pytest.mark.xfail(reason="#710 and #712") def test_unicode_files(tarfile_with_unicode, tmpdir): target = tmpdir / 'out' - archive_util.unpack_archive(tarfile_with_unicode, six.text_type(target)) + archive_util.unpack_archive(tarfile_with_unicode, str(target)) diff --git a/setuptools/tests/test_bdist_deprecations.py b/setuptools/tests/test_bdist_deprecations.py new file mode 100644 index 00000000..704164aa --- /dev/null +++ b/setuptools/tests/test_bdist_deprecations.py @@ -0,0 +1,23 @@ +"""develop tests +""" +import mock + +import pytest + +from setuptools.dist import Distribution +from setuptools import SetuptoolsDeprecationWarning + + +@mock.patch("distutils.command.bdist_wininst.bdist_wininst") +def test_bdist_wininst_warning(distutils_cmd): + dist = Distribution(dict( + script_name='setup.py', + script_args=['bdist_wininst'], + name='foo', + py_modules=['hi'], + )) + dist.parse_command_line() + with pytest.warns(SetuptoolsDeprecationWarning): + dist.run_commands() + + distutils_cmd.run.assert_called_once() diff --git a/setuptools/tests/test_build_ext.py b/setuptools/tests/test_build_ext.py index 3dc87ca3..838fdb42 100644 --- a/setuptools/tests/test_build_ext.py +++ b/setuptools/tests/test_build_ext.py @@ -2,8 +2,6 @@ import sys import distutils.command.build_ext as orig from distutils.sysconfig import get_config_var -from setuptools.extern import six - from setuptools.command.build_ext import build_ext, get_abi3_suffix from setuptools.dist import Distribution from setuptools.extension import Extension @@ -41,8 +39,8 @@ class TestBuildExt: assert 'spam.eggs' in cmd.ext_map res = cmd.get_ext_filename('spam.eggs') - if six.PY2 or not get_abi3_suffix(): - assert res.endswith(get_config_var('SO')) + if not get_abi3_suffix(): + assert res.endswith(get_config_var('EXT_SUFFIX')) elif sys.platform == 'win32': assert res.endswith('eggs.pyd') else: diff --git a/setuptools/tests/test_build_meta.py b/setuptools/tests/test_build_meta.py index 8fcf3055..5462b26a 100644 --- a/setuptools/tests/test_build_meta.py +++ b/setuptools/tests/test_build_meta.py @@ -1,20 +1,13 @@ -from __future__ import unicode_literals - import os import shutil import tarfile +import importlib +from concurrent import futures import pytest from .files import build_files from .textwrap import DALS -from . import py2_only - -__metaclass__ = type - -# Backports on Python 2.7 -import importlib -from concurrent import futures class BuildBackendBase: @@ -220,15 +213,6 @@ class TestBuildMetaBackend: assert os.path.isfile(os.path.join(dist_dir, dist_info, 'METADATA')) - @py2_only - def test_prepare_metadata_for_build_wheel_with_str(self, build_backend): - dist_dir = os.path.abspath(str('pip-dist-info')) - os.makedirs(dist_dir) - - dist_info = build_backend.prepare_metadata_for_build_wheel(dist_dir) - - assert os.path.isfile(os.path.join(dist_dir, dist_info, 'METADATA')) - def test_build_sdist_explicit_dist(self, build_backend): # explicitly specifying the dist folder should work # the folder sdist_directory and the ``--dist-dir`` can be the same @@ -380,7 +364,7 @@ class TestBuildMetaBackend: setup( name="qux", version="0.0.0", - py_modules=["hello.py"], + py_modules=["hello"], setup_requires={setup_literal}, ) """).format(setup_literal=setup_literal), @@ -407,6 +391,35 @@ class TestBuildMetaBackend: assert expected == sorted(actual) + def test_dont_install_setup_requires(self, tmpdir_cwd): + files = { + 'setup.py': DALS(""" + from setuptools import setup + + setup( + name="qux", + version="0.0.0", + py_modules=["hello"], + setup_requires=["does-not-exist >99"], + ) + """), + 'hello.py': DALS(""" + def run(): + print('hello') + """), + } + + build_files(files) + + build_backend = self.get_build_backend() + + dist_dir = os.path.abspath('pip-dist-info') + os.makedirs(dist_dir) + + # does-not-exist can't be satisfied, so if it attempts to install + # setup_requires, it will fail. + build_backend.prepare_metadata_for_build_wheel(dist_dir) + _sys_argv_0_passthrough = { 'setup.py': DALS(""" import os diff --git a/setuptools/tests/test_build_py.py b/setuptools/tests/test_build_py.py index b3a99f56..78a31ac4 100644 --- a/setuptools/tests/test_build_py.py +++ b/setuptools/tests/test_build_py.py @@ -1,4 +1,8 @@ import os +import stat +import shutil + +import pytest from setuptools.dist import Distribution @@ -20,3 +24,61 @@ def test_directories_in_package_data_glob(tmpdir_cwd): os.makedirs('path/subpath') dist.parse_command_line() dist.run_commands() + + +def test_read_only(tmpdir_cwd): + """ + Ensure read-only flag is not preserved in copy + for package modules and package data, as that + causes problems with deleting read-only files on + Windows. + + #1451 + """ + dist = Distribution(dict( + script_name='setup.py', + script_args=['build_py'], + packages=['pkg'], + package_data={'pkg': ['data.dat']}, + name='pkg', + )) + os.makedirs('pkg') + open('pkg/__init__.py', 'w').close() + open('pkg/data.dat', 'w').close() + os.chmod('pkg/__init__.py', stat.S_IREAD) + os.chmod('pkg/data.dat', stat.S_IREAD) + dist.parse_command_line() + dist.run_commands() + shutil.rmtree('build') + + +@pytest.mark.xfail( + 'platform.system() == "Windows"', + reason="On Windows, files do not have executable bits", + raises=AssertionError, + strict=True, +) +def test_executable_data(tmpdir_cwd): + """ + Ensure executable bit is preserved in copy for + package data, as users rely on it for scripts. + + #2041 + """ + dist = Distribution(dict( + script_name='setup.py', + script_args=['build_py'], + packages=['pkg'], + package_data={'pkg': ['run-me']}, + name='pkg', + )) + os.makedirs('pkg') + open('pkg/__init__.py', 'w').close() + open('pkg/run-me', 'w').close() + os.chmod('pkg/run-me', 0o700) + + dist.parse_command_line() + dist.run_commands() + + assert os.stat('build/lib/pkg/run-me').st_mode & stat.S_IEXEC, \ + "Script is not executable" diff --git a/setuptools/tests/test_config.py b/setuptools/tests/test_config.py index 2fa0b374..1dee1271 100644 --- a/setuptools/tests/test_config.py +++ b/setuptools/tests/test_config.py @@ -1,15 +1,12 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - import contextlib +import configparser + import pytest from distutils.errors import DistutilsOptionError, DistutilsFileError from mock import patch from setuptools.dist import Distribution, _Distribution from setuptools.config import ConfigHandler, read_configuration -from setuptools.extern.six.moves import configparser -from . import py2_only, py3_only from .textwrap import DALS @@ -53,6 +50,7 @@ def fake_env( ' return [3, 4, 5, "dev"]\n' '\n' ) + return package_dir, config @@ -267,11 +265,23 @@ class TestMetadata: def test_version(self, tmpdir): - _, config = fake_env( + package_dir, config = fake_env( tmpdir, '[metadata]\n' 'version = attr: fake_package.VERSION\n' ) + + sub_a = package_dir.mkdir('subpkg_a') + sub_a.join('__init__.py').write('') + sub_a.join('mod.py').write('VERSION = (2016, 11, 26)') + + sub_b = package_dir.mkdir('subpkg_b') + sub_b.join('__init__.py').write('') + sub_b.join('mod.py').write( + 'import third_party_module\n' + 'VERSION = (2016, 11, 26)' + ) + with get_dist(tmpdir) as dist: assert dist.metadata.version == '1.2.3' @@ -289,13 +299,16 @@ class TestMetadata: with get_dist(tmpdir) as dist: assert dist.metadata.version == '1' - subpack = tmpdir.join('fake_package').mkdir('subpackage') - subpack.join('__init__.py').write('') - subpack.join('submodule.py').write('VERSION = (2016, 11, 26)') + config.write( + '[metadata]\n' + 'version = attr: fake_package.subpkg_a.mod.VERSION\n' + ) + with get_dist(tmpdir) as dist: + assert dist.metadata.version == '2016.11.26' config.write( '[metadata]\n' - 'version = attr: fake_package.subpackage.submodule.VERSION\n' + 'version = attr: fake_package.subpkg_b.mod.VERSION\n' ) with get_dist(tmpdir) as dist: assert dist.metadata.version == '2016.11.26' @@ -697,19 +710,6 @@ class TestOptions: assert set(dist.packages) == set( ['fake_package', 'fake_package.sub_two']) - @py2_only - def test_find_namespace_directive_fails_on_py2(self, tmpdir): - dir_package, config = fake_env( - tmpdir, - '[options]\n' - 'packages = find_namespace:\n' - ) - - with pytest.raises(DistutilsOptionError): - with get_dist(tmpdir) as dist: - dist.parse_config_files() - - @py3_only def test_find_namespace_directive(self, tmpdir): dir_package, config = fake_env( tmpdir, diff --git a/setuptools/tests/test_develop.py b/setuptools/tests/test_develop.py index 792975fd..9854420e 100644 --- a/setuptools/tests/test_develop.py +++ b/setuptools/tests/test_develop.py @@ -1,8 +1,6 @@ """develop tests """ -from __future__ import absolute_import, unicode_literals - import os import site import sys @@ -10,13 +8,13 @@ import io import subprocess import platform -from setuptools.extern import six from setuptools.command import test import pytest from setuptools.command.develop import develop from setuptools.dist import Distribution +from setuptools.tests import ack_2to3 from . import contexts from . import namespaces @@ -65,6 +63,7 @@ class TestDevelop: @pytest.mark.skipif( in_virtualenv or in_venv, reason="Cannot run when invoked in a virtualenv or venv") + @ack_2to3 def test_2to3_user_mode(self, test_env): settings = dict( name='foo', @@ -95,7 +94,7 @@ class TestDevelop: with io.open(fn) as init_file: init = init_file.read().strip() - expected = 'print "foo"' if six.PY2 else 'print("foo")' + expected = 'print("foo")' assert init == expected def test_console_scripts(self, tmpdir): @@ -161,7 +160,7 @@ class TestNamespaces: reason="https://github.com/pypa/setuptools/issues/851", ) @pytest.mark.skipif( - platform.python_implementation() == 'PyPy' and not six.PY2, + platform.python_implementation() == 'PyPy', reason="https://github.com/pypa/setuptools/issues/1202", ) def test_namespace_package_importable(self, tmpdir): diff --git a/setuptools/tests/test_dist.py b/setuptools/tests/test_dist.py index 6e8c45fd..cb47fb58 100644 --- a/setuptools/tests/test_dist.py +++ b/setuptools/tests/test_dist.py @@ -1,20 +1,17 @@ -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals - import io import collections import re +import functools +import urllib.request +import urllib.parse from distutils.errors import DistutilsSetupError from setuptools.dist import ( _get_unpatched, check_package_data, DistDeprecationWarning, ) +from setuptools import sic from setuptools import Distribution -from setuptools.extern.six.moves.urllib.request import pathname2url -from setuptools.extern.six.moves.urllib_parse import urljoin -from setuptools.extern import six from .textwrap import DALS from .test_easy_install import make_nspkg_sdist @@ -27,7 +24,8 @@ def test_dist_fetch_build_egg(tmpdir): Check multiple calls to `Distribution.fetch_build_egg` work as expected. """ index = tmpdir.mkdir('index') - index_url = urljoin('file://', pathname2url(str(index))) + index_url = urllib.parse.urljoin( + 'file://', urllib.request.pathname2url(str(index))) def sdist_with_index(distname, version): dist_dir = index.mkdir(distname) @@ -61,8 +59,7 @@ def test_dist_fetch_build_egg(tmpdir): dist.fetch_build_egg(r) for r in reqs ] - # noqa below because on Python 2 it causes flakes - assert [dist.key for dist in resolved_dists if dist] == reqs # noqa + assert [dist.key for dist in resolved_dists if dist] == reqs def test_dist__get_unpatched_deprecated(): @@ -70,75 +67,72 @@ def test_dist__get_unpatched_deprecated(): def __read_test_cases(): - # Metadata version 1.0 - base_attrs = { - "name": "package", - "version": "0.0.1", - "author": "Foo Bar", - "author_email": "foo@bar.net", - "long_description": "Long\ndescription", - "description": "Short description", - "keywords": ["one", "two"] - } - - def merge_dicts(d1, d2): - d1 = d1.copy() - d1.update(d2) - - return d1 + base = dict( + name="package", + version="0.0.1", + author="Foo Bar", + author_email="foo@bar.net", + long_description="Long\ndescription", + description="Short description", + keywords=["one", "two"], + ) + + params = functools.partial(dict, base) test_cases = [ - ('Metadata version 1.0', base_attrs.copy()), - ('Metadata version 1.1: Provides', merge_dicts(base_attrs, { - 'provides': ['package'] - })), - ('Metadata version 1.1: Obsoletes', merge_dicts(base_attrs, { - 'obsoletes': ['foo'] - })), - ('Metadata version 1.1: Classifiers', merge_dicts(base_attrs, { - 'classifiers': [ + ('Metadata version 1.0', params()), + ('Metadata version 1.1: Provides', params( + provides=['package'], + )), + ('Metadata version 1.1: Obsoletes', params( + obsoletes=['foo'], + )), + ('Metadata version 1.1: Classifiers', params( + classifiers=[ 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'License :: OSI Approved :: MIT License', - ]})), - ('Metadata version 1.1: Download URL', merge_dicts(base_attrs, { - 'download_url': 'https://example.com' - })), - ('Metadata Version 1.2: Requires-Python', merge_dicts(base_attrs, { - 'python_requires': '>=3.7' - })), + ], + )), + ('Metadata version 1.1: Download URL', params( + download_url='https://example.com', + )), + ('Metadata Version 1.2: Requires-Python', params( + python_requires='>=3.7', + )), pytest.param( 'Metadata Version 1.2: Project-Url', - merge_dicts(base_attrs, { - 'project_urls': { - 'Foo': 'https://example.bar' - } - }), marks=pytest.mark.xfail( - reason="Issue #1578: project_urls not read" - )), - ('Metadata Version 2.1: Long Description Content Type', - merge_dicts(base_attrs, { - 'long_description_content_type': 'text/x-rst; charset=UTF-8' - })), + params(project_urls=dict(Foo='https://example.bar')), + marks=pytest.mark.xfail( + reason="Issue #1578: project_urls not read", + ), + ), + ('Metadata Version 2.1: Long Description Content Type', params( + long_description_content_type='text/x-rst; charset=UTF-8', + )), pytest.param( 'Metadata Version 2.1: Provides Extra', - merge_dicts(base_attrs, { - 'provides_extras': ['foo', 'bar'] - }), marks=pytest.mark.xfail(reason="provides_extras not read")), - ('Missing author, missing author e-mail', - {'name': 'foo', 'version': '1.0.0'}), - ('Missing author', - {'name': 'foo', - 'version': '1.0.0', - 'author_email': 'snorri@sturluson.name'}), - ('Missing author e-mail', - {'name': 'foo', - 'version': '1.0.0', - 'author': 'Snorri Sturluson'}), - ('Missing author', - {'name': 'foo', - 'version': '1.0.0', - 'author': 'Snorri Sturluson'}), + params(provides_extras=['foo', 'bar']), + marks=pytest.mark.xfail(reason="provides_extras not read"), + ), + ('Missing author', dict( + name='foo', + version='1.0.0', + author_email='snorri@sturluson.name', + )), + ('Missing author e-mail', dict( + name='foo', + version='1.0.0', + author='Snorri Sturluson', + )), + ('Missing author and e-mail', dict( + name='foo', + version='1.0.0', + )), + ('Bypass normalized version', dict( + name='foo', + version=sic('1.0.0a'), + )), ] return test_cases @@ -151,10 +145,7 @@ def test_read_metadata(name, attrs): dist_class = metadata_out.__class__ # Write to PKG_INFO and then load into a new metadata object - if six.PY2: - PKG_INFO = io.BytesIO() - else: - PKG_INFO = io.StringIO() + PKG_INFO = io.StringIO() metadata_out.write_pkg_file(PKG_INFO) diff --git a/setuptools/tests/test_dist_info.py b/setuptools/tests/test_dist_info.py index f7e7d2bf..29fbd09d 100644 --- a/setuptools/tests/test_dist_info.py +++ b/setuptools/tests/test_dist_info.py @@ -1,10 +1,6 @@ """Test .dist-info style distributions. """ -from __future__ import unicode_literals - -from setuptools.extern.six.moves import map - import pytest import pkg_resources diff --git a/setuptools/tests/test_distutils_adoption.py b/setuptools/tests/test_distutils_adoption.py new file mode 100644 index 00000000..a53773df --- /dev/null +++ b/setuptools/tests/test_distutils_adoption.py @@ -0,0 +1,71 @@ +import os +import sys +import functools +import subprocess +import platform + +import pytest +import jaraco.envs +import path + + +IS_PYPY = '__pypy__' in sys.builtin_module_names + + +class VirtualEnv(jaraco.envs.VirtualEnv): + name = '.env' + + def run(self, cmd, *args, **kwargs): + cmd = [self.exe(cmd[0])] + cmd[1:] + return subprocess.check_output(cmd, *args, cwd=self.root, **kwargs) + + +@pytest.fixture +def venv(tmpdir): + env = VirtualEnv() + env.root = path.Path(tmpdir) + env.req = os.getcwd() + return env.create() + + +def popen_text(call): + """ + Augment the Popen call with the parameters to ensure unicode text. + """ + return functools.partial(call, universal_newlines=True) \ + if sys.version_info < (3, 7) else functools.partial(call, text=True) + + +def find_distutils(venv, imports='distutils', env=None, **kwargs): + py_cmd = 'import {imports}; print(distutils.__file__)'.format(**locals()) + cmd = ['python', '-c', py_cmd] + if platform.system() == 'Windows': + env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] + return popen_text(venv.run)(cmd, env=env, **kwargs) + + +def test_distutils_stdlib(venv): + """ + Ensure stdlib distutils is used when appropriate. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='stdlib') + assert venv.name not in find_distutils(venv, env=env).split(os.sep) + + +def test_distutils_local_with_setuptools(venv): + """ + Ensure local distutils is used when appropriate. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='local') + loc = find_distutils(venv, imports='setuptools, distutils', env=env) + assert venv.name in loc.split(os.sep) + + +@pytest.mark.xfail('IS_PYPY', reason='pypy imports distutils on startup') +def test_distutils_local(venv): + """ + Even without importing, the setuptools-local copy of distutils is + preferred. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='local') + assert venv.name in find_distutils(venv, env=env).split(os.sep) diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py index 534392b9..26a5e9a6 100644 --- a/setuptools/tests/test_easy_install.py +++ b/setuptools/tests/test_easy_install.py @@ -1,7 +1,5 @@ -# -*- coding: utf-8 -*- """Easy install Tests """ -from __future__ import absolute_import, unicode_literals import sys import os @@ -16,8 +14,7 @@ import io import zipfile import mock import time - -from setuptools.extern import six +import re import pytest @@ -40,8 +37,6 @@ from . import contexts from .files import build_files from .textwrap import DALS -__metaclass__ = type - class FakeDist: def get_entry_map(self, group): @@ -61,35 +56,17 @@ SETUP_PY = DALS(""" class TestEasyInstallTest: - def test_install_site_py(self, tmpdir): - dist = Distribution() - cmd = ei.easy_install(dist) - cmd.sitepy_installed = False - cmd.install_dir = str(tmpdir) - cmd.install_site_py() - assert (tmpdir / 'site.py').exists() - def test_get_script_args(self): header = ei.CommandSpec.best().from_environment().as_header() - expected = header + DALS(r""" - # EASY-INSTALL-ENTRY-SCRIPT: 'spec','console_scripts','name' - __requires__ = 'spec' - import re - import sys - from pkg_resources import load_entry_point - - if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit( - load_entry_point('spec', 'console_scripts', 'name')() - ) - """) # noqa: E501 dist = FakeDist() - args = next(ei.ScriptWriter.get_args(dist)) name, script = itertools.islice(args, 2) - - assert script == expected + assert script.startswith(header) + assert "'spec'" in script + assert "'console_scripts'" in script + assert "'name'" in script + assert re.search( + '^# EASY-INSTALL-ENTRY-SCRIPT', script, flags=re.MULTILINE) def test_no_find_links(self): # new option '--no-find-links', that blocks find-links added at @@ -738,7 +715,7 @@ class TestSetupRequires: dep_2_0_url=dep_2_0_url, dep_2_0_sdist=dep_2_0_sdist, dep_2_0_python_requires=dep_2_0_python_requires, - ), 'utf-8') + ), 'utf-8') index_url = path_to_url(str(index)) with contexts.save_pkg_resources_state(): test_pkg = create_setup_requires_package( @@ -1001,8 +978,6 @@ def create_setup_requires_package(path, distname='foobar', version='0.1', ) class TestScriptHeader: non_ascii_exe = '/Users/José/bin/python' - if six.PY2: - non_ascii_exe = non_ascii_exe.encode('utf-8') exe_with_spaces = r'C:\Program Files\Python36\python.exe' def test_get_script_header(self): diff --git a/setuptools/tests/test_egg_info.py b/setuptools/tests/test_egg_info.py index 109f9135..dc472af4 100644 --- a/setuptools/tests/test_egg_info.py +++ b/setuptools/tests/test_egg_info.py @@ -10,7 +10,6 @@ from setuptools.command.egg_info import ( egg_info, manifest_maker, EggInfoDeprecationWarning, get_pkg_info_revision, ) from setuptools.dist import Distribution -from setuptools.extern.six.moves import map import pytest @@ -19,8 +18,6 @@ from .files import build_files from .textwrap import DALS from . import contexts -__metaclass__ = type - class Environment(str): pass @@ -73,8 +70,7 @@ class TestEggInfo: """ When the egg_info section is empty or not present, running save_version_info should add the settings to the setup.cfg - in a deterministic order, consistent with the ordering found - on Python 2.7 with PYTHONHASHSEED=0. + in a deterministic order. """ setup_cfg = os.path.join(env.paths['home'], 'setup.cfg') dist = Distribution() @@ -906,49 +902,3 @@ class TestEggInfo: def test_get_pkg_info_revision_deprecated(self): pytest.warns(EggInfoDeprecationWarning, get_pkg_info_revision) - - EGG_INFO_TESTS = ( - # Check for issue #1136: invalid string type when - # reading declarative `setup.cfg` under Python 2. - { - 'setup.py': DALS( - """ - from setuptools import setup - setup( - name="foo", - ) - """), - 'setup.cfg': DALS( - """ - [options] - package_dir = - = src - """), - 'src': {}, - }, - # Check Unicode can be used in `setup.py` under Python 2. - { - 'setup.py': DALS( - """ - # -*- coding: utf-8 -*- - from __future__ import unicode_literals - from setuptools import setup, find_packages - setup( - name="foo", - package_dir={'': 'src'}, - ) - """), - 'src': {}, - } - ) - - @pytest.mark.parametrize('package_files', EGG_INFO_TESTS) - def test_egg_info(self, tmpdir_cwd, env, package_files): - """ - """ - build_files(package_files) - code, data = environment.run_setup_py( - cmd=['egg_info'], - data_stream=1, - ) - assert not code, data diff --git a/setuptools/tests/test_extern.py b/setuptools/tests/test_extern.py new file mode 100644 index 00000000..0d6b164f --- /dev/null +++ b/setuptools/tests/test_extern.py @@ -0,0 +1,20 @@ +import importlib +import pickle + +from setuptools import Distribution +from setuptools.extern import ordered_set + + +def test_reimport_extern(): + ordered_set2 = importlib.import_module(ordered_set.__name__) + assert ordered_set is ordered_set2 + + +def test_orderedset_pickle_roundtrip(): + o1 = ordered_set.OrderedSet([1, 2, 5]) + o2 = pickle.loads(pickle.dumps(o1)) + assert o1 == o2 + + +def test_distribution_picklable(): + pickle.loads(pickle.dumps(Distribution())) diff --git a/setuptools/tests/test_find_packages.py b/setuptools/tests/test_find_packages.py index ab26b4f1..906713f6 100644 --- a/setuptools/tests/test_find_packages.py +++ b/setuptools/tests/test_find_packages.py @@ -7,12 +7,8 @@ import platform import pytest -from . import py3_only - -from setuptools.extern.six import PY3 from setuptools import find_packages -if PY3: - from setuptools import find_namespace_packages +from setuptools import find_namespace_packages # modeled after CPython's test.support.can_symlink @@ -154,34 +150,29 @@ class TestFindPackages: def _assert_packages(self, actual, expected): assert set(actual) == set(expected) - @py3_only def test_pep420_ns_package(self): packages = find_namespace_packages( self.dist_dir, include=['pkg*'], exclude=['pkg.subpkg.assets']) self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) - @py3_only def test_pep420_ns_package_no_includes(self): packages = find_namespace_packages( self.dist_dir, exclude=['pkg.subpkg.assets']) self._assert_packages( packages, ['docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg']) - @py3_only def test_pep420_ns_package_no_includes_or_excludes(self): packages = find_namespace_packages(self.dist_dir) expected = [ 'docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg', 'pkg.subpkg.assets'] self._assert_packages(packages, expected) - @py3_only def test_regular_package_with_nested_pep420_ns_packages(self): self._touch('__init__.py', self.pkg_dir) packages = find_namespace_packages( self.dist_dir, exclude=['docs', 'pkg.subpkg.assets']) self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) - @py3_only def test_pep420_ns_package_no_non_package_dirs(self): shutil.rmtree(self.docs_dir) shutil.rmtree(os.path.join(self.dist_dir, 'pkg/subpkg/assets')) diff --git a/setuptools/tests/test_integration.py b/setuptools/tests/test_integration.py index f1a27f8b..24cef480 100644 --- a/setuptools/tests/test_integration.py +++ b/setuptools/tests/test_integration.py @@ -11,8 +11,8 @@ import subprocess import functools import tarfile import zipfile +import urllib.request -from setuptools.extern.six.moves import urllib import pytest from setuptools.command.easy_install import easy_install diff --git a/setuptools/tests/test_manifest.py b/setuptools/tests/test_manifest.py index 2a0e9c86..82bdb9c6 100644 --- a/setuptools/tests/test_manifest.py +++ b/setuptools/tests/test_manifest.py @@ -7,19 +7,16 @@ import shutil import sys import tempfile import itertools +import io from distutils import log from distutils.errors import DistutilsTemplateError -import pkg_resources.py31compat from setuptools.command.egg_info import FileList, egg_info, translate_pattern from setuptools.dist import Distribution -from setuptools.extern import six from setuptools.tests.textwrap import DALS import pytest -__metaclass__ = type - def make_local_path(s): """Converts '/' in a string to os.sep""" @@ -42,7 +39,7 @@ setup(**%r) @contextlib.contextmanager def quiet(): old_stdout, old_stderr = sys.stdout, sys.stderr - sys.stdout, sys.stderr = six.StringIO(), six.StringIO() + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() try: yield finally: @@ -364,7 +361,7 @@ class TestFileListTest(TempDirTestCase): for file in files: file = os.path.join(self.temp_dir, file) dirname, basename = os.path.split(file) - pkg_resources.py31compat.makedirs(dirname, exist_ok=True) + os.makedirs(dirname, exist_ok=True) open(file, 'w').close() def test_process_template_line(self): diff --git a/setuptools/tests/test_msvc14.py b/setuptools/tests/test_msvc14.py new file mode 100644 index 00000000..1aca12dd --- /dev/null +++ b/setuptools/tests/test_msvc14.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +""" +Tests for msvc support module (msvc14 unit tests). +""" + +import os +from distutils.errors import DistutilsPlatformError +import pytest +import sys + + +@pytest.mark.skipif(sys.platform != "win32", + reason="These tests are only for win32") +class TestMSVC14: + """Python 3.8 "distutils/tests/test_msvccompiler.py" backport""" + def test_no_compiler(self): + import setuptools.msvc as _msvccompiler + # makes sure query_vcvarsall raises + # a DistutilsPlatformError if the compiler + # is not found + + def _find_vcvarsall(plat_spec): + return None, None + + old_find_vcvarsall = _msvccompiler._msvc14_find_vcvarsall + _msvccompiler._msvc14_find_vcvarsall = _find_vcvarsall + try: + pytest.raises(DistutilsPlatformError, + _msvccompiler._msvc14_get_vc_env, + 'wont find this version') + finally: + _msvccompiler._msvc14_find_vcvarsall = old_find_vcvarsall + + def test_get_vc_env_unicode(self): + import setuptools.msvc as _msvccompiler + + test_var = 'ṰḖṤṪ┅ṼẨṜ' + test_value = '₃⁴₅' + + # Ensure we don't early exit from _get_vc_env + old_distutils_use_sdk = os.environ.pop('DISTUTILS_USE_SDK', None) + os.environ[test_var] = test_value + try: + env = _msvccompiler._msvc14_get_vc_env('x86') + assert test_var.lower() in env + assert test_value == env[test_var.lower()] + finally: + os.environ.pop(test_var) + if old_distutils_use_sdk: + os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk + + def test_get_vc2017(self): + import setuptools.msvc 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._msvc14_find_vc2017() + if os.environ.get('APPVEYOR_BUILD_WORKER_IMAGE', '') in [ + 'Visual Studio 2017' + ]: + assert version + if version: + assert version >= 15 + assert os.path.isdir(path) + else: + pytest.skip("VS 2017 is not installed") + + def test_get_vc2015(self): + import setuptools.msvc 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._msvc14_find_vc2015() + if os.environ.get('APPVEYOR_BUILD_WORKER_IMAGE', '') in [ + 'Visual Studio 2015', 'Visual Studio 2017' + ]: + assert version + if version: + assert version >= 14 + assert os.path.isdir(path) + else: + pytest.skip("VS 2015 is not installed") diff --git a/setuptools/tests/test_namespaces.py b/setuptools/tests/test_namespaces.py index f937d981..6c8c522d 100644 --- a/setuptools/tests/test_namespaces.py +++ b/setuptools/tests/test_namespaces.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, unicode_literals - import sys import subprocess diff --git a/setuptools/tests/test_packageindex.py b/setuptools/tests/test_packageindex.py index 60d968fd..8e9435ef 100644 --- a/setuptools/tests/test_packageindex.py +++ b/setuptools/tests/test_packageindex.py @@ -1,17 +1,15 @@ -from __future__ import absolute_import - import sys import os import distutils.errors +import platform +import urllib.request +import urllib.error +import http.client -from setuptools.extern import six -from setuptools.extern.six.moves import urllib, http_client import mock import pytest -import pkg_resources import setuptools.package_index -from setuptools.tests.server import IndexServer from .textwrap import DALS @@ -61,7 +59,7 @@ class TestPackageIndex: ) def _urlopen(*args): - raise http_client.BadStatusLine('line') + raise http.client.BadStatusLine('line') index.opener = _urlopen url = 'http://example.com' @@ -85,7 +83,7 @@ class TestPackageIndex: try: index.open_url(url) except distutils.errors.DistutilsError as error: - msg = six.text_type(error) + msg = str(error) assert ( 'nonnumeric port' in msg or 'getaddrinfo failed' in msg @@ -114,43 +112,6 @@ class TestPackageIndex: url = 'file:///tmp/test_package_index' assert index.url_ok(url, True) - def test_links_priority(self): - """ - Download links from the pypi simple index should be used before - external download links. - https://bitbucket.org/tarek/distribute/issue/163 - - Usecase : - - someone uploads a package on pypi, a md5 is generated - - someone manually copies this link (with the md5 in the url) onto an - external page accessible from the package page. - - someone reuploads the package (with a different md5) - - while easy_installing, an MD5 error occurs because the external link - is used - -> Setuptools should use the link from pypi, not the external one. - """ - if sys.platform.startswith('java'): - # Skip this test on jython because binding to :0 fails - return - - # start an index server - server = IndexServer() - server.start() - index_url = server.base_url() + 'test_links_priority/simple/' - - # scan a test index - pi = setuptools.package_index.PackageIndex(index_url) - requirement = pkg_resources.Requirement.parse('foobar') - pi.find_packages(requirement) - server.stop() - - # the distribution has been found - assert 'foobar' in pi - # we have only one link, because links are compared without md5 - assert len(pi['foobar']) == 1 - # the link should be from the index - assert 'correct_md5' in pi['foobar'][0].location - def test_parse_bdist_wininst(self): parse = setuptools.package_index.parse_bdist_wininst @@ -221,11 +182,11 @@ class TestPackageIndex: ('+ubuntu_0', '+ubuntu.0'), ] versions = [ - [''.join([e, r, p, l]) for l in ll] + [''.join([e, r, p, loc]) for loc in locs] for e in epoch for r in releases for p in sum([pre, post, dev], ['']) - for ll in local] + for locs in local] for v, vc in versions: dists = list(setuptools.package_index.distros_for_url( 'http://example.com/example.zip#egg=example-' + v)) @@ -322,17 +283,27 @@ class TestContentCheckers: assert rep == 'My message about md5' +@pytest.fixture +def temp_home(tmpdir, monkeypatch): + key = ( + 'USERPROFILE' + if platform.system() == 'Windows' and sys.version_info > (3, 8) else + 'HOME' + ) + + monkeypatch.setitem(os.environ, key, str(tmpdir)) + return tmpdir + + class TestPyPIConfig: - def test_percent_in_password(self, tmpdir, monkeypatch): - monkeypatch.setitem(os.environ, 'HOME', str(tmpdir)) - pypirc = tmpdir / '.pypirc' - with pypirc.open('w') as strm: - strm.write(DALS(""" - [pypi] - repository=https://pypi.org - username=jaraco - password=pity% - """)) + def test_percent_in_password(self, temp_home): + pypirc = temp_home / '.pypirc' + pypirc.write(DALS(""" + [pypi] + repository=https://pypi.org + username=jaraco + password=pity% + """)) cfg = setuptools.package_index.PyPIConfig() cred = cfg.creds_by_repository['https://pypi.org'] assert cred.username == 'jaraco' diff --git a/setuptools/tests/test_sdist.py b/setuptools/tests/test_sdist.py index 0bea53df..049fdcc0 100644 --- a/setuptools/tests/test_sdist.py +++ b/setuptools/tests/test_sdist.py @@ -1,8 +1,5 @@ -# -*- coding: utf-8 -*- """sdist tests""" -from __future__ import print_function, unicode_literals - import os import sys import tempfile @@ -10,9 +7,6 @@ import unicodedata import contextlib import io -from setuptools.extern import six -from setuptools.extern.six.moves import map - import pytest import pkg_resources @@ -21,7 +15,6 @@ from setuptools.command.egg_info import manifest_maker from setuptools.dist import Distribution from setuptools.tests import fail_on_ascii from .text import Filenames -from . import py3_only SETUP_ATTRS = { @@ -42,7 +35,7 @@ setup(**%r) @contextlib.contextmanager def quiet(): old_stdout, old_stderr = sys.stdout, sys.stderr - sys.stdout, sys.stderr = six.StringIO(), six.StringIO() + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() try: yield finally: @@ -51,7 +44,7 @@ def quiet(): # Convert to POSIX path def posix(path): - if not six.PY2 and not isinstance(path, str): + if not isinstance(path, str): return path.replace(os.sep.encode('ascii'), b'/') else: return path.replace(os.sep, '/') @@ -59,7 +52,7 @@ def posix(path): # HFS Plus uses decomposed UTF-8 def decompose(path): - if isinstance(path, six.text_type): + if isinstance(path, str): return unicodedata.normalize('NFD', path) try: path = path.decode('utf-8') @@ -231,7 +224,6 @@ class TestSdistTest: # The manifest should contain the UTF-8 filename assert posix(filename) in u_contents - @py3_only @fail_on_ascii def test_write_manifest_allows_utf8_filenames(self): # Test for #303. @@ -265,7 +257,6 @@ class TestSdistTest: # The filelist should have been updated as well assert u_filename in mm.filelist.files - @py3_only def test_write_manifest_skips_non_utf8_filenames(self): """ Files that cannot be encoded to UTF-8 (specifically, those that @@ -329,11 +320,9 @@ class TestSdistTest: cmd.read_manifest() # The filelist should contain the UTF-8 filename - if not six.PY2: - filename = filename.decode('utf-8') + filename = filename.decode('utf-8') assert filename in cmd.filelist.files - @py3_only @fail_on_latin1_encoded_filenames def test_read_manifest_skips_non_utf8_filenames(self): # Test for #303. @@ -383,21 +372,18 @@ class TestSdistTest: if sys.platform == 'darwin': filename = decompose(filename) - if not six.PY2: - fs_enc = sys.getfilesystemencoding() + fs_enc = sys.getfilesystemencoding() - if sys.platform == 'win32': - if fs_enc == 'cp1252': - # Python 3 mangles the UTF-8 filename - filename = filename.decode('cp1252') - assert filename in cmd.filelist.files - else: - filename = filename.decode('mbcs') - assert filename in cmd.filelist.files + if sys.platform == 'win32': + if fs_enc == 'cp1252': + # Python mangles the UTF-8 filename + filename = filename.decode('cp1252') + assert filename in cmd.filelist.files else: - filename = filename.decode('utf-8') + filename = filename.decode('mbcs') assert filename in cmd.filelist.files else: + filename = filename.decode('utf-8') assert filename in cmd.filelist.files @classmethod @@ -425,33 +411,20 @@ class TestSdistTest: with quiet(): cmd.run() - if six.PY2: - # Under Python 2 there seems to be no decoded string in the - # filelist. However, due to decode and encoding of the - # file name to get utf-8 Manifest the latin1 maybe excluded - try: - # fs_enc should match how one is expect the decoding to - # be proformed for the manifest output. - fs_enc = sys.getfilesystemencoding() - filename.decode(fs_enc) - assert filename in cmd.filelist.files - except UnicodeDecodeError: - filename not in cmd.filelist.files - else: - # not all windows systems have a default FS encoding of cp1252 - if sys.platform == 'win32': - # Latin-1 is similar to Windows-1252 however - # on mbcs filesys it is not in latin-1 encoding - fs_enc = sys.getfilesystemencoding() - if fs_enc != 'mbcs': - fs_enc = 'latin-1' - filename = filename.decode(fs_enc) + # not all windows systems have a default FS encoding of cp1252 + if sys.platform == 'win32': + # Latin-1 is similar to Windows-1252 however + # on mbcs filesys it is not in latin-1 encoding + fs_enc = sys.getfilesystemencoding() + if fs_enc != 'mbcs': + fs_enc = 'latin-1' + filename = filename.decode(fs_enc) - assert filename in cmd.filelist.files - else: - # The Latin-1 filename should have been skipped - filename = filename.decode('latin-1') - filename not in cmd.filelist.files + assert filename in cmd.filelist.files + else: + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + filename not in cmd.filelist.files def test_pyproject_toml_in_sdist(self, tmpdir): """ diff --git a/setuptools/tests/test_setopt.py b/setuptools/tests/test_setopt.py index 1b038954..0163f9af 100644 --- a/setuptools/tests/test_setopt.py +++ b/setuptools/tests/test_setopt.py @@ -1,13 +1,7 @@ -# coding: utf-8 - -from __future__ import unicode_literals - import io - -import six +import configparser from setuptools.command import setopt -from setuptools.extern.six.moves import configparser class TestEdit: @@ -15,7 +9,7 @@ class TestEdit: def parse_config(filename): parser = configparser.ConfigParser() with io.open(filename, encoding='utf-8') as reader: - (parser.readfp if six.PY2 else parser.read_file)(reader) + parser.read_file(reader) return parser @staticmethod diff --git a/setuptools/tests/test_setuptools.py b/setuptools/tests/test_setuptools.py index bca69c30..42f8e18b 100644 --- a/setuptools/tests/test_setuptools.py +++ b/setuptools/tests/test_setuptools.py @@ -4,7 +4,7 @@ import sys import os import distutils.core import distutils.cmd -from distutils.errors import DistutilsOptionError, DistutilsPlatformError +from distutils.errors import DistutilsOptionError from distutils.errors import DistutilsSetupError from distutils.core import Extension from distutils.version import LooseVersion @@ -14,9 +14,7 @@ import pytest import setuptools import setuptools.dist import setuptools.depends as dep -from setuptools import Feature from setuptools.depends import Require -from setuptools.extern import six def makeSetup(**args): @@ -50,7 +48,7 @@ class TestDepends: x = "test" y = z - fc = six.get_function_code(f1) + fc = f1.__code__ # unrecognized name assert dep.extract_constant(fc, 'q', -1) is None @@ -216,86 +214,6 @@ class TestDistro: self.dist.exclude(package_dir=['q']) -@pytest.mark.filterwarnings('ignore:Features are deprecated') -class TestFeatures: - def setup_method(self, method): - self.req = Require('Distutils', '1.0.3', 'distutils') - self.dist = makeSetup( - features={ - 'foo': Feature( - "foo", standard=True, require_features=['baz', self.req]), - 'bar': Feature("bar", standard=True, packages=['pkg.bar'], - py_modules=['bar_et'], remove=['bar.ext'], - ), - 'baz': Feature( - "baz", optional=False, packages=['pkg.baz'], - scripts=['scripts/baz_it'], - libraries=[('libfoo', 'foo/foofoo.c')] - ), - 'dwim': Feature("DWIM", available=False, remove='bazish'), - }, - script_args=['--without-bar', 'install'], - packages=['pkg.bar', 'pkg.foo'], - py_modules=['bar_et', 'bazish'], - ext_modules=[Extension('bar.ext', ['bar.c'])] - ) - - def testDefaults(self): - assert not Feature( - "test", standard=True, remove='x', available=False - ).include_by_default() - assert Feature("test", standard=True, remove='x').include_by_default() - # Feature must have either kwargs, removes, or require_features - with pytest.raises(DistutilsSetupError): - Feature("test") - - def testAvailability(self): - with pytest.raises(DistutilsPlatformError): - self.dist.features['dwim'].include_in(self.dist) - - def testFeatureOptions(self): - dist = self.dist - assert ( - ('with-dwim', None, 'include DWIM') in dist.feature_options - ) - assert ( - ('without-dwim', None, 'exclude DWIM (default)') - in dist.feature_options - ) - assert ( - ('with-bar', None, 'include bar (default)') in dist.feature_options - ) - assert ( - ('without-bar', None, 'exclude bar') in dist.feature_options - ) - assert dist.feature_negopt['without-foo'] == 'with-foo' - assert dist.feature_negopt['without-bar'] == 'with-bar' - assert dist.feature_negopt['without-dwim'] == 'with-dwim' - assert ('without-baz' not in dist.feature_negopt) - - def testUseFeatures(self): - dist = self.dist - assert dist.with_foo == 1 - assert dist.with_bar == 0 - assert dist.with_baz == 1 - assert ('bar_et' not in dist.py_modules) - assert ('pkg.bar' not in dist.packages) - assert ('pkg.baz' in dist.packages) - assert ('scripts/baz_it' in dist.scripts) - assert (('libfoo', 'foo/foofoo.c') in dist.libraries) - assert dist.ext_modules == [] - assert dist.require_features == [self.req] - - # If we ask for bar, it should fail because we explicitly disabled - # it on the command line - with pytest.raises(DistutilsOptionError): - dist.include_feature('bar') - - def testFeatureWithInvalidRemove(self): - with pytest.raises(SystemExit): - makeSetup(features={'x': Feature('x', remove='y')}) - - class TestCommandTests: def testTestIsCommand(self): test_cmd = makeSetup().get_command_obj('test') diff --git a/setuptools/tests/test_test.py b/setuptools/tests/test_test.py index 8ee70a7e..180562e2 100644 --- a/setuptools/tests/test_test.py +++ b/setuptools/tests/test_test.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals - import mock from distutils import log import os @@ -10,6 +6,7 @@ import pytest from setuptools.command.test import test from setuptools.dist import Distribution +from setuptools.tests import ack_2to3 from .textwrap import DALS @@ -74,6 +71,7 @@ def quiet_log(): @pytest.mark.usefixtures('sample_test', 'quiet_log') +@ack_2to3 def test_test(capfd): params = dict( name='foo', @@ -108,7 +106,6 @@ def test_tests_are_run_once(capfd): with open('dummy/test_dummy.py', 'wt') as f: f.write(DALS( """ - from __future__ import print_function import unittest class TestTest(unittest.TestCase): def test_test(self): @@ -124,6 +121,7 @@ def test_tests_are_run_once(capfd): @pytest.mark.usefixtures('sample_test') +@ack_2to3 def test_warns_deprecation(capfd): params = dict( name='foo', @@ -149,6 +147,7 @@ def test_warns_deprecation(capfd): @pytest.mark.usefixtures('sample_test') +@ack_2to3 def test_deprecation_stderr(capfd): params = dict( name='foo', diff --git a/setuptools/tests/test_virtualenv.py b/setuptools/tests/test_virtualenv.py index 6549a6c0..b555ce4f 100644 --- a/setuptools/tests/test_virtualenv.py +++ b/setuptools/tests/test_virtualenv.py @@ -13,17 +13,6 @@ from .test_easy_install import make_nspkg_sdist @pytest.fixture(autouse=True) -def disable_requires_python(monkeypatch): - """ - Disable Requires-Python on Python 2.7 - """ - if sys.version_info > (3,): - return - - monkeypatch.setenv('PIP_IGNORE_REQUIRES_PYTHON', 'true') - - -@pytest.fixture(autouse=True) def pytest_virtualenv_works(virtualenv): """ pytest_virtualenv may not work. if it doesn't, skip these @@ -57,10 +46,7 @@ def test_clean_env_install(bare_virtualenv): """ Check setuptools can be installed in a clean environment. """ - bare_virtualenv.run(' && '.join(( - 'cd {source}', - 'python setup.py install', - )).format(source=SOURCE_DIR)) + bare_virtualenv.run(['python', 'setup.py', 'install'], cd=SOURCE_DIR) def _get_pip_versions(): @@ -115,10 +101,9 @@ def test_pip_upgrade_from_source(pip_version, virtualenv): dist_dir = virtualenv.workspace # Generate source distribution / wheel. virtualenv.run(' && '.join(( - 'cd {source}', 'python setup.py -q sdist -d {dist}', 'python setup.py -q bdist_wheel -d {dist}', - )).format(source=SOURCE_DIR, dist=dist_dir)) + )).format(dist=dist_dir), cd=SOURCE_DIR) sdist = glob.glob(os.path.join(dist_dir, '*.zip'))[0] wheel = glob.glob(os.path.join(dist_dir, '*.whl'))[0] # Then update from wheel. @@ -183,10 +168,8 @@ def _check_test_command_install_requirements(virtualenv, tmpdir): open('success', 'w').close() ''')) # Run test command for test package. - virtualenv.run(' && '.join(( - 'cd {tmpdir}', - 'python setup.py test -s test', - )).format(tmpdir=tmpdir)) + virtualenv.run( + ['python', 'setup.py', 'test', '-s', 'test'], cd=str(tmpdir)) assert tmpdir.join('success').check() @@ -207,7 +190,5 @@ def test_no_missing_dependencies(bare_virtualenv): Quick and dirty test to ensure all external dependencies are vendored. """ for command in ('upload',): # sorted(distutils.command.__all__): - bare_virtualenv.run(' && '.join(( - 'cd {source}', - 'python setup.py {command} -h', - )).format(command=command, source=SOURCE_DIR)) + bare_virtualenv.run( + ['python', 'setup.py', command, '-h'], cd=SOURCE_DIR) diff --git a/setuptools/tests/test_wheel.py b/setuptools/tests/test_wheel.py index f72ccbbf..e56eac14 100644 --- a/setuptools/tests/test_wheel.py +++ b/setuptools/tests/test_wheel.py @@ -25,8 +25,6 @@ from .contexts import tempdir from .files import build_files from .textwrap import DALS -__metaclass__ = type - WHEEL_INFO_TESTS = ( ('invalid.whl', ValueError), diff --git a/setuptools/tests/test_windows_wrappers.py b/setuptools/tests/test_windows_wrappers.py index 2553394a..fa647de8 100644 --- a/setuptools/tests/test_windows_wrappers.py +++ b/setuptools/tests/test_windows_wrappers.py @@ -12,8 +12,6 @@ the script they are to wrap and with the same name as the script they are to wrap. """ -from __future__ import absolute_import - import sys import textwrap import subprocess diff --git a/setuptools/tests/text.py b/setuptools/tests/text.py index ad2c6249..e05cc633 100644 --- a/setuptools/tests/text.py +++ b/setuptools/tests/text.py @@ -1,8 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals - - class Filenames: unicode = 'smörbröd.py' latin_1 = unicode.encode('latin-1') diff --git a/setuptools/tests/textwrap.py b/setuptools/tests/textwrap.py index 5cd9e5bc..5e39618d 100644 --- a/setuptools/tests/textwrap.py +++ b/setuptools/tests/textwrap.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import textwrap |