diff --git a/docs/pip_sphinxext.py b/docs/pip_sphinxext.py index a0e69c6e4..29ca34c72 100644 --- a/docs/pip_sphinxext.py +++ b/docs/pip_sphinxext.py @@ -42,15 +42,16 @@ class PipCommandDescription(rst.Directive): class PipOptions(rst.Directive): def _format_option(self, option, cmd_name=None): - if cmd_name: - bookmark_line = ".. _`%s_%s`:" % (cmd_name, option._long_opts[0]) - else: - bookmark_line = ".. _`%s`:" % option._long_opts[0] + bookmark_line = ( + ".. _`{cmd_name}_{option._long_opts[0]}`:" + if cmd_name else + ".. _`{option._long_opts[0]}`:" + ).format(**locals()) line = ".. option:: " if option._short_opts: line += option._short_opts[0] if option._short_opts and option._long_opts: - line += ", %s" % option._long_opts[0] + line += ", " + option._long_opts[0] elif option._long_opts: line += option._long_opts[0] if option.takes_value(): @@ -60,7 +61,7 @@ class PipOptions(rst.Directive): opt_help = option.help.replace('%default', str(option.default)) # fix paths with sys.prefix opt_help = opt_help.replace(sys.prefix, "") - return [bookmark_line, "", line, "", " %s" % opt_help, ""] + return [bookmark_line, "", line, "", " " + opt_help, ""] def _format_options(self, options, cmd_name=None): for option in options: diff --git a/news/7826.feature b/news/7826.feature new file mode 100644 index 000000000..7c6897cc8 --- /dev/null +++ b/news/7826.feature @@ -0,0 +1 @@ +Replaced remaining uses of '%' formatting with .format. Fixed two regressions introduced in earlier attempts. diff --git a/src/pip/_internal/cli/main_parser.py b/src/pip/_internal/cli/main_parser.py index 4871956c9..08c82c1f7 100644 --- a/src/pip/_internal/cli/main_parser.py +++ b/src/pip/_internal/cli/main_parser.py @@ -48,7 +48,7 @@ def create_main_parser(): # create command listing for description description = [''] + [ - '%-27s %s' % (name, command_info.summary) + '{name:27} {command_info.summary}'.format(**locals()) for name, command_info in commands_dict.items() ] parser.description = '\n'.join(description) diff --git a/src/pip/_internal/cli/parser.py b/src/pip/_internal/cli/parser.py index e799215be..04e00b721 100644 --- a/src/pip/_internal/cli/parser.py +++ b/src/pip/_internal/cli/parser.py @@ -31,14 +31,14 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter): optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs) def format_option_strings(self, option): - return self._format_option_strings(option, ' <%s>', ', ') + return self._format_option_strings(option) def _format_option_strings(self, option, mvarfmt=' <{}>', optsep=', '): """ Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') - :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar + :param mvarfmt: metavar format string :param optsep: separator """ opts = [] diff --git a/src/pip/_internal/cli/progress_bars.py b/src/pip/_internal/cli/progress_bars.py index 7ed224790..f9a68104e 100644 --- a/src/pip/_internal/cli/progress_bars.py +++ b/src/pip/_internal/cli/progress_bars.py @@ -14,7 +14,7 @@ from pip._internal.utils.misc import format_size from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: - from typing import Any, Dict, List + from typing import Any, Dict, Iterator, List, Tuple try: from pip._vendor import colorama @@ -124,7 +124,7 @@ class SilentBar(Bar): class BlueEmojiBar(IncrementalBar): - suffix = "%(percent)d%%" + suffix = "{percent:.0f}%" bar_prefix = " " bar_suffix = " " phases = (u"\U0001F539", u"\U0001F537", u"\U0001F535") # type: Any @@ -203,8 +203,8 @@ class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin, DownloadProgressMixin): file = sys.stdout - message = "%(percent)d%%" - suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" + message = "{percent:.0f}%" + suffix = "{downloaded} {download_speed} {pretty_eta}" # NOTE: The "type: ignore" comments on the following classes are there to # work around https://github.com/python/typing/issues/241 @@ -238,7 +238,7 @@ class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, DownloadProgressMixin, Spinner): file = sys.stdout - suffix = "%(downloaded)s %(download_speed)s" + suffix = "{downloaded} {download_speed}" def next_phase(self): # type: ignore if not hasattr(self, "_phaser"): @@ -247,19 +247,22 @@ class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, def update(self): # type: () -> None - message = self.message % self + vals = dict(self._load_vals( + 'downloaded', 'download_speed', 'pretty_eta', 'percent')) + message = self.message.format(**vals) phase = self.next_phase() - suffix = self.suffix % self - line = ''.join([ - message, - " " if message else "", - phase, - " " if suffix else "", - suffix, - ]) - + suffix = self.suffix.format(**vals) + line = " ".join(filter(None, (message, phase, suffix))) self.writeln(line) + def _load_vals(self, *names): + # type: (*str) -> Iterator[Tuple[str, Any]] + for name in names: + try: + yield name, getattr(self, name) + except Exception: + pass + BAR_TYPES = { "off": (DownloadSilentBar, DownloadSilentBar), diff --git a/src/pip/_internal/cli/req_command.py b/src/pip/_internal/cli/req_command.py index 21770df62..45ddb8b47 100644 --- a/src/pip/_internal/cli/req_command.py +++ b/src/pip/_internal/cli/req_command.py @@ -342,13 +342,13 @@ class RequirementCommand(IndexGroupCommand): opts = {'name': self.name} if options.find_links: raise CommandError( - 'You must give at least one requirement to %(name)s ' - '(maybe you meant "pip %(name)s %(links)s"?)' % - dict(opts, links=' '.join(options.find_links))) + 'You must give at least one requirement to {name} ' + '(maybe you meant "pip {name} {links}"?)'.format( + **dict(opts, links=' '.join(options.find_links)))) else: raise CommandError( - 'You must give at least one requirement to %(name)s ' - '(see "pip help %(name)s")' % opts) + 'You must give at least one requirement to {name} ' + '(see "pip help {name}")'.format(**opts)) return requirements diff --git a/src/pip/_internal/cli/spinners.py b/src/pip/_internal/cli/spinners.py index 3d152a807..c6c4c5cd1 100644 --- a/src/pip/_internal/cli/spinners.py +++ b/src/pip/_internal/cli/spinners.py @@ -106,7 +106,8 @@ class NonInteractiveSpinner(SpinnerInterface): # type: (str) -> None if self._finished: return - self._update("finished with status '%s'" % (final_status,)) + self._update( + "finished with status '{final_status}'".format(**locals())) self._finished = True diff --git a/src/pip/_internal/commands/completion.py b/src/pip/_internal/commands/completion.py index e0b743e54..910fcbfe3 100644 --- a/src/pip/_internal/commands/completion.py +++ b/src/pip/_internal/commands/completion.py @@ -10,29 +10,29 @@ from pip._internal.cli.base_command import Command from pip._internal.utils.misc import get_prog BASE_COMPLETION = """ -# pip %(shell)s completion start%(script)s# pip %(shell)s completion end +# pip {shell} completion start{script}# pip {shell} completion end """ COMPLETION_SCRIPTS = { 'bash': """ _pip_completion() - { - COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \\ + {{ + COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\ COMP_CWORD=$COMP_CWORD \\ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) - } - complete -o default -F _pip_completion %(prog)s + }} + complete -o default -F _pip_completion {prog} """, 'zsh': """ - function _pip_completion { + function _pip_completion {{ local words cword read -Ac words read -cn cword reply=( $( COMP_WORDS="$words[*]" \\ COMP_CWORD=$(( cword-1 )) \\ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )) - } - compctl -K _pip_completion %(prog)s + }} + compctl -K _pip_completion {prog} """, 'fish': """ function __fish_complete_pip @@ -43,7 +43,7 @@ COMPLETION_SCRIPTS = { set -lx PIP_AUTO_COMPLETE 1 string split \\ -- (eval $COMP_WORDS[1]) end - complete -fa "(__fish_complete_pip)" -c %(prog)s + complete -fa "(__fish_complete_pip)" -c {prog} """, } @@ -85,11 +85,10 @@ class CompletionCommand(Command): shell_options = ['--' + shell for shell in sorted(shells)] if options.shell in shells: script = textwrap.dedent( - COMPLETION_SCRIPTS.get(options.shell, '') % { - 'prog': get_prog(), - } + COMPLETION_SCRIPTS.get(options.shell, '').format( + prog=get_prog()) ) - print(BASE_COMPLETION % {'script': script, 'shell': options.shell}) + print(BASE_COMPLETION.format(script=script, shell=options.shell)) else: sys.stderr.write( 'ERROR: You must pass {}\n' .format(' or '.join(shell_options)) diff --git a/src/pip/_internal/commands/search.py b/src/pip/_internal/commands/search.py index 2e880eec2..e5f286ea5 100644 --- a/src/pip/_internal/commands/search.py +++ b/src/pip/_internal/commands/search.py @@ -121,8 +121,9 @@ def print_results(hits, name_column_width=None, terminal_width=None): summary = textwrap.wrap(summary, target_width) summary = ('\n' + ' ' * (name_column_width + 3)).join(summary) - line = '%-*s - %s' % (name_column_width, - '%s (%s)' % (name, latest), summary) + line = '{name_latest:{name_column_width}} - {summary}'.format( + name_latest='{name} ({latest})'.format(**locals()), + **locals()) try: write_output(line) if name in installed_packages: diff --git a/src/pip/_internal/commands/uninstall.py b/src/pip/_internal/commands/uninstall.py index e93ad74e2..5db4fb467 100644 --- a/src/pip/_internal/commands/uninstall.py +++ b/src/pip/_internal/commands/uninstall.py @@ -73,8 +73,8 @@ class UninstallCommand(Command, SessionCommandMixin): reqs_to_uninstall[canonicalize_name(req.name)] = req if not reqs_to_uninstall: raise InstallationError( - 'You must give at least one requirement to %(name)s (see ' - '"pip help %(name)s")' % dict(name=self.name) + 'You must give at least one requirement to {self.name} (see ' + '"pip help {self.name}")'.format(**locals()) ) protect_pip_from_modification_on_windows( diff --git a/src/pip/_internal/models/link.py b/src/pip/_internal/models/link.py index 0b30ab251..c3e743d39 100644 --- a/src/pip/_internal/models/link.py +++ b/src/pip/_internal/models/link.py @@ -96,7 +96,8 @@ class Link(KeyBasedCompareMixin): return netloc name = urllib_parse.unquote(name) - assert name, ('URL %r produced no filename' % self._url) + assert name, ( + 'URL {self._url!r} produced no filename'.format(**locals())) return name @property diff --git a/src/pip/_internal/operations/install/wheel.py b/src/pip/_internal/operations/install/wheel.py index b1a76a24c..329d90c67 100644 --- a/src/pip/_internal/operations/install/wheel.py +++ b/src/pip/_internal/operations/install/wheel.py @@ -17,6 +17,7 @@ import stat import sys import warnings from base64 import urlsafe_b64encode +from itertools import starmap from zipfile import ZipFile from pip._vendor import pkg_resources @@ -534,13 +535,9 @@ def install_unpacked_wheel( del console[k] # Generate the console and GUI entry points specified in the wheel - scripts_to_generate.extend( - '%s = %s' % kv for kv in console.items() - ) + scripts_to_generate.extend(starmap('{} = {}'.format, console.items())) - gui_scripts_to_generate = [ - '%s = %s' % kv for kv in gui.items() - ] + gui_scripts_to_generate = list(starmap('{} = {}'.format, gui.items())) generated_console_scripts = [] # type: List[str] diff --git a/src/pip/_internal/req/constructors.py b/src/pip/_internal/req/constructors.py index 395157c4b..195b0d0be 100644 --- a/src/pip/_internal/req/constructors.py +++ b/src/pip/_internal/req/constructors.py @@ -281,8 +281,8 @@ def _get_url_from_path(path, name): if is_installable_dir(path): return path_to_url(path) raise InstallationError( - "Directory %r is not installable. Neither 'setup.py' " - "nor 'pyproject.toml' found." % name + "Directory {name!r} is not installable. Neither 'setup.py' " + "nor 'pyproject.toml' found.".format(**locals()) ) if not is_archive_file(path): return None @@ -339,7 +339,7 @@ def parse_req_from_line(name, line_source): # wheel file if link.is_wheel: wheel = Wheel(link.filename) # can raise InvalidWheelFilename - req_as_string = "%s==%s" % (wheel.name, wheel.version) + req_as_string = "{wheel.name}=={wheel.version}".format(**locals()) else: # set the req to the egg fragment. when it's not there, this # will become an 'unnamed' requirement diff --git a/src/pip/_internal/req/req_install.py b/src/pip/_internal/req/req_install.py index 5926a17de..dccb0c795 100644 --- a/src/pip/_internal/req/req_install.py +++ b/src/pip/_internal/req/req_install.py @@ -639,7 +639,8 @@ class InstallRequirement(object): if self.link.scheme == 'file': # Static paths don't get updated return - assert '+' in self.link.url, "bad url: %r" % self.link.url + assert '+' in self.link.url, \ + "bad url: {self.link.url!r}".format(**locals()) vc_type, url = self.link.url.split('+', 1) vcs_backend = vcs.get_backend(vc_type) if vcs_backend: @@ -701,7 +702,8 @@ class InstallRequirement(object): def _clean_zip_name(name, prefix): # type: (str, str) -> str assert name.startswith(prefix + os.path.sep), ( - "name %r doesn't start with prefix %r" % (name, prefix) + "name {name!r} doesn't start with prefix {prefix!r}" + .format(**locals()) ) name = name[len(prefix) + 1:] name = name.replace(os.path.sep, '/') diff --git a/src/pip/_internal/req/req_set.py b/src/pip/_internal/req/req_set.py index dc76cce9b..bc8e32264 100644 --- a/src/pip/_internal/req/req_set.py +++ b/src/pip/_internal/req/req_set.py @@ -194,7 +194,7 @@ class RequirementSet(object): if project_name in self.requirements: return self.requirements[project_name] - raise KeyError("No project with the name %r" % name) + raise KeyError("No project with the name {name!r}".format(**locals())) @property def all_requirements(self): diff --git a/src/pip/_internal/utils/compat.py b/src/pip/_internal/utils/compat.py index 08c292d18..d939e21fe 100644 --- a/src/pip/_internal/utils/compat.py +++ b/src/pip/_internal/utils/compat.py @@ -64,7 +64,7 @@ if PY2: raw_bytes = (err.object[i] for i in range(err.start, err.end)) # Python 2 gave us characters - convert to numeric bytes raw_bytes = (ord(b) for b in raw_bytes) - return u"".join(u"\\x%x" % c for c in raw_bytes), err.end + return u"".join(map(u"\\x{:x}".format, raw_bytes)), err.end codecs.register_error( "backslashreplace_decode", backslashreplace_decode_fn, diff --git a/src/pip/_internal/utils/filesystem.py b/src/pip/_internal/utils/filesystem.py index 6f1537e40..161c450aa 100644 --- a/src/pip/_internal/utils/filesystem.py +++ b/src/pip/_internal/utils/filesystem.py @@ -73,7 +73,8 @@ def copy2_fixed(src, dest): pass else: if is_socket_file: - raise shutil.SpecialFileError("`%s` is a socket" % f) + raise shutil.SpecialFileError( + "`{f}` is a socket".format(**locals())) raise diff --git a/src/pip/_internal/utils/logging.py b/src/pip/_internal/utils/logging.py index 7767111a6..134f7908d 100644 --- a/src/pip/_internal/utils/logging.py +++ b/src/pip/_internal/utils/logging.py @@ -156,7 +156,7 @@ class IndentingFormatter(logging.Formatter): if self.add_timestamp: # TODO: Use Formatter.default_time_format after dropping PY2. t = self.formatTime(record, "%Y-%m-%dT%H:%M:%S") - prefix = '%s,%03d ' % (t, record.msecs) + prefix = '{t},{record.msecs:03.0f} '.format(**locals()) prefix += " " * get_indentation() formatted = "".join([ prefix + line diff --git a/src/pip/_internal/utils/misc.py b/src/pip/_internal/utils/misc.py index 5ad0544be..a36701a70 100644 --- a/src/pip/_internal/utils/misc.py +++ b/src/pip/_internal/utils/misc.py @@ -266,13 +266,13 @@ def ask_password(message): def format_size(bytes): # type: (float) -> str if bytes > 1000 * 1000: - return '%.1f MB' % (bytes / 1000.0 / 1000) + return '{:.1f} MB'.format(bytes / 1000.0 / 1000) elif bytes > 10 * 1000: - return '%i kB' % (bytes / 1000) + return '{} kB'.format(int(bytes / 1000)) elif bytes > 1000: - return '%.1f kB' % (bytes / 1000.0) + return '{:.1f} kB'.format(bytes / 1000.0) else: - return '%i bytes' % bytes + return '{} bytes'.format(int(bytes)) def is_installable_dir(path): diff --git a/src/pip/_internal/utils/urls.py b/src/pip/_internal/utils/urls.py index 9ad40feb3..f37bc8f90 100644 --- a/src/pip/_internal/utils/urls.py +++ b/src/pip/_internal/utils/urls.py @@ -34,7 +34,8 @@ def url_to_path(url): Convert a file: URL to a path. """ assert url.startswith('file:'), ( - "You can only turn file: urls into filenames (not %r)" % url) + "You can only turn file: urls into filenames (not {url!r})" + .format(**locals())) _, netloc, path, _, _ = urllib_parse.urlsplit(url) @@ -46,8 +47,8 @@ def url_to_path(url): netloc = '\\\\' + netloc else: raise ValueError( - 'non-local file URIs are not supported on this platform: %r' - % url + 'non-local file URIs are not supported on this platform: {url!r}' + .format(**locals()) ) path = urllib_request.url2pathname(netloc + path) diff --git a/src/pip/_internal/vcs/subversion.py b/src/pip/_internal/vcs/subversion.py index 6c76d1ad4..0ec659744 100644 --- a/src/pip/_internal/vcs/subversion.py +++ b/src/pip/_internal/vcs/subversion.py @@ -151,7 +151,8 @@ class Subversion(VersionControl): elif data.startswith('=40.8.0.' % path_to_url(project_dir)) in result.stderr + result.returncode != 0 and ( + 'Some build dependencies for {url} conflict ' + 'with PEP 517/518 supported ' + 'requirements: setuptools==1.0 is incompatible with ' + 'setuptools>=40.8.0.' + .format(url=path_to_url(project_dir))) in result.stderr ), str(result) @@ -198,12 +200,13 @@ def test_pip_second_command_line_interface_works( if pyversion_tuple < (2, 7, 9): kwargs['expect_stderr'] = True - args = ['pip%s' % pyversion] + args = ['pip{pyversion}'.format(**globals())] args.extend(['install', 'INITools==0.2']) args.extend(['-f', data.packages]) result = script.run(*args, **kwargs) egg_info_folder = ( - script.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion + script.site_packages / + 'INITools-0.2-py{pyversion}.egg-info'.format(**globals()) ) initools_folder = script.site_packages / 'initools' assert egg_info_folder in result.files_created, str(result) @@ -234,7 +237,8 @@ def test_basic_install_from_pypi(script): """ result = script.pip('install', 'INITools==0.2') egg_info_folder = ( - script.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion + script.site_packages / + 'INITools-0.2-py{pyversion}.egg-info'.format(**globals()) ) initools_folder = script.site_packages / 'initools' assert egg_info_folder in result.files_created, str(result) @@ -281,7 +285,10 @@ def test_basic_install_editable_from_svn(script): def _test_install_editable_from_git(script, tmpdir): """Test cloning from Git.""" pkg_path = _create_test_package(script, name='testpackage', vcs='git') - args = ['install', '-e', 'git+%s#egg=testpackage' % path_to_url(pkg_path)] + args = [ + 'install', '-e', + 'git+{url}#egg=testpackage'.format(url=path_to_url(pkg_path)), + ] result = script.pip(*args) result.assert_installed('testpackage', with_files=['.git']) @@ -310,10 +317,10 @@ def test_install_editable_uninstalls_existing(data, script, tmpdir): result = script.pip( 'install', '-e', - '%s#egg=pip-test-package' % - local_checkout( - 'git+https://github.com/pypa/pip-test-package.git', tmpdir, - ), + '{dir}#egg=pip-test-package'.format( + dir=local_checkout( + 'git+https://github.com/pypa/pip-test-package.git', tmpdir, + )), ) result.assert_installed('pip-test-package', with_files=['.git']) assert 'Found existing installation: pip-test-package 0.1' in result.stdout @@ -362,7 +369,9 @@ def test_vcs_url_final_slash_normalization(script, tmpdir): Test that presence or absence of final slash in VCS URL is normalized. """ pkg_path = _create_test_package(script, name='testpackage', vcs='hg') - args = ['install', '-e', 'hg+%s/#egg=testpackage' % path_to_url(pkg_path)] + args = [ + 'install', + '-e', 'hg+{url}/#egg=testpackage'.format(url=path_to_url(pkg_path))] result = script.pip(*args) result.assert_installed('testpackage', with_files=['.hg']) @@ -371,7 +380,9 @@ def test_vcs_url_final_slash_normalization(script, tmpdir): def test_install_editable_from_bazaar(script, tmpdir): """Test checking out from Bazaar.""" pkg_path = _create_test_package(script, name='testpackage', vcs='bazaar') - args = ['install', '-e', 'bzr+%s/#egg=testpackage' % path_to_url(pkg_path)] + args = [ + 'install', + '-e', 'bzr+{url}/#egg=testpackage'.format(url=path_to_url(pkg_path))] result = script.pip(*args) result.assert_installed('testpackage', with_files=['.bzr']) @@ -384,12 +395,13 @@ def test_vcs_url_urlquote_normalization(script, tmpdir): """ script.pip( 'install', '-e', - '%s/#egg=django-wikiapp' % - local_checkout( - 'bzr+http://bazaar.launchpad.net/%7Edjango-wikiapp/django-wikiapp' - '/release-0.1', - tmpdir, - ), + '{url}/#egg=django-wikiapp'.format( + url=local_checkout( + 'bzr+http://bazaar.launchpad.net/' + '%7Edjango-wikiapp/django-wikiapp' + '/release-0.1', + tmpdir, + )), ) @@ -401,7 +413,8 @@ def test_basic_install_from_local_directory(script, data): result = script.pip('install', to_install) fspkg_folder = script.site_packages / 'fspkg' egg_info_folder = ( - script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion + script.site_packages / + 'FSPkg-0.1.dev0-py{pyversion}.egg-info'.format(**globals()) ) assert fspkg_folder in result.files_created, str(result.stdout) assert egg_info_folder in result.files_created, str(result) @@ -420,7 +433,8 @@ def test_basic_install_relative_directory(script, data, test_type, editable): Test installing a requirement using a relative path. """ egg_info_file = ( - script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion + script.site_packages / + 'FSPkg-0.1.dev0-py{pyversion}.egg-info'.format(**globals()) ) egg_link_file = ( script.site_packages / 'FSPkg.egg-link' @@ -550,7 +564,8 @@ def test_install_from_local_directory_with_symlinks_to_directories( result = script.pip('install', to_install) pkg_folder = script.site_packages / 'symlinks' egg_info_folder = ( - script.site_packages / 'symlinks-0.1.dev0-py%s.egg-info' % pyversion + script.site_packages / + 'symlinks-0.1.dev0-py{pyversion}.egg-info'.format(**globals()) ) assert pkg_folder in result.files_created, str(result.stdout) assert egg_info_folder in result.files_created, str(result) @@ -562,7 +577,8 @@ def test_install_from_local_directory_with_socket_file(script, data, tmpdir): Test installing from a local directory containing a socket file. """ egg_info_file = ( - script.site_packages / "FSPkg-0.1.dev0-py%s.egg-info" % pyversion + script.site_packages / + "FSPkg-0.1.dev0-py{pyversion}.egg-info".format(**globals()) ) package_folder = script.site_packages / "fspkg" to_copy = data.packages.joinpath("FSPkg") @@ -663,7 +679,8 @@ def test_install_curdir(script, data): result = script.pip('install', curdir, cwd=run_from) fspkg_folder = script.site_packages / 'fspkg' egg_info_folder = ( - script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion + script.site_packages / + 'FSPkg-0.1.dev0-py{pyversion}.egg-info'.format(**globals()) ) assert fspkg_folder in result.files_created, str(result.stdout) assert egg_info_folder in result.files_created, str(result) @@ -677,7 +694,8 @@ def test_install_pardir(script, data): result = script.pip('install', pardir, cwd=run_from) fspkg_folder = script.site_packages / 'fspkg' egg_info_folder = ( - script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion + script.site_packages / + 'FSPkg-0.1.dev0-py{pyversion}.egg-info'.format(**globals()) ) assert fspkg_folder in result.files_created, str(result.stdout) assert egg_info_folder in result.files_created, str(result) @@ -714,9 +732,9 @@ def test_install_using_install_option_and_editable(script, tmpdir): script.scratch_path.joinpath(folder).mkdir() url = 'git+git://github.com/pypa/pip-test-package' result = script.pip( - 'install', '-e', '%s#egg=pip-test-package' % - local_checkout(url, tmpdir), - '--install-option=--script-dir=%s' % folder, + 'install', '-e', '{url}#egg=pip-test-package' + .format(url=local_checkout(url, tmpdir)), + '--install-option=--script-dir={folder}'.format(**locals()), expect_stderr=True) script_file = ( script.venv / 'src' / 'pip-test-package' / @@ -735,7 +753,7 @@ def test_install_global_option_using_editable(script, tmpdir): url = 'hg+http://bitbucket.org/runeh/anyjson' result = script.pip( 'install', '--global-option=--version', '-e', - '%s@0.2.5#egg=anyjson' % local_checkout(url, tmpdir), + '{url}@0.2.5#egg=anyjson'.format(url=local_checkout(url, tmpdir)), expect_stderr=True) assert 'Successfully installed anyjson' in result.stdout @@ -747,7 +765,10 @@ def test_install_package_with_same_name_in_curdir(script): """ script.scratch_path.joinpath("mock==0.6").mkdir() result = script.pip('install', 'mock==0.6') - egg_folder = script.site_packages / 'mock-0.6.0-py%s.egg-info' % pyversion + egg_folder = ( + script.site_packages / + 'mock-0.6.0-py{pyversion}.egg-info'.format(**globals()) + ) assert egg_folder in result.files_created, str(result) @@ -765,7 +786,10 @@ def test_install_folder_using_dot_slash(script): pkg_path = script.scratch_path / 'mock' pkg_path.joinpath("setup.py").write_text(mock100_setup_py) result = script.pip('install', './mock') - egg_folder = script.site_packages / 'mock-100.1-py%s.egg-info' % pyversion + egg_folder = ( + script.site_packages / + 'mock-100.1-py{pyversion}.egg-info'.format(**globals()) + ) assert egg_folder in result.files_created, str(result) @@ -777,7 +801,10 @@ def test_install_folder_using_slash_in_the_end(script): pkg_path = script.scratch_path / 'mock' pkg_path.joinpath("setup.py").write_text(mock100_setup_py) result = script.pip('install', 'mock' + os.path.sep) - egg_folder = script.site_packages / 'mock-100.1-py%s.egg-info' % pyversion + egg_folder = ( + script.site_packages / + 'mock-100.1-py{pyversion}.egg-info'.format(**globals()) + ) assert egg_folder in result.files_created, str(result) @@ -790,7 +817,10 @@ def test_install_folder_using_relative_path(script): pkg_path = script.scratch_path / 'initools' / 'mock' pkg_path.joinpath("setup.py").write_text(mock100_setup_py) result = script.pip('install', Path('initools') / 'mock') - egg_folder = script.site_packages / 'mock-100.1-py%s.egg-info' % pyversion + egg_folder = ( + script.site_packages / + 'mock-100.1-py{pyversion}.egg-info'.format(**globals()) + ) assert egg_folder in result.files_created, str(result) @@ -802,8 +832,8 @@ def test_install_package_which_contains_dev_in_name(script): result = script.pip('install', 'django-devserver==0.0.4') devserver_folder = script.site_packages / 'devserver' egg_info_folder = ( - script.site_packages / 'django_devserver-0.0.4-py%s.egg-info' % - pyversion + script.site_packages / + 'django_devserver-0.0.4-py{pyversion}.egg-info'.format(**globals()) ) assert devserver_folder in result.files_created, str(result.stdout) assert egg_info_folder in result.files_created, str(result) @@ -832,7 +862,8 @@ def test_install_package_with_target(script): str(result) ) egg_folder = ( - Path('scratch') / 'target' / 'simple-2.0-py%s.egg-info' % pyversion) + Path('scratch') / 'target' / + 'simple-2.0-py{pyversion}.egg-info'.format(**globals())) assert egg_folder in result.files_created, ( str(result) ) @@ -966,8 +997,8 @@ def test_install_package_with_root(script, data): 'simple==1.0', ) normal_install_path = ( - script.base_path / script.site_packages / 'simple-1.0-py%s.egg-info' % - pyversion + script.base_path / script.site_packages / + 'simple-1.0-py{pyversion}.egg-info'.format(**globals()) ) # use distutils to change the root exactly how the --root option does it from distutils.util import change_root @@ -1090,9 +1121,11 @@ def test_url_req_case_mismatch_no_index(script, data): ) # only Upper-1.0.tar.gz should get installed. - egg_folder = script.site_packages / 'Upper-1.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Upper-1.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder in result.files_created, str(result) - egg_folder = script.site_packages / 'Upper-2.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Upper-2.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder not in result.files_created, str(result) @@ -1117,9 +1150,11 @@ def test_url_req_case_mismatch_file_index(script, data): ) # only Upper-1.0.tar.gz should get installed. - egg_folder = script.site_packages / 'Dinner-1.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Dinner-1.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder in result.files_created, str(result) - egg_folder = script.site_packages / 'Dinner-2.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Dinner-2.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder not in result.files_created, str(result) @@ -1134,9 +1169,11 @@ def test_url_incorrect_case_no_index(script, data): ) # only Upper-2.0.tar.gz should get installed. - egg_folder = script.site_packages / 'Upper-1.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Upper-1.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder not in result.files_created, str(result) - egg_folder = script.site_packages / 'Upper-2.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Upper-2.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder in result.files_created, str(result) @@ -1152,9 +1189,11 @@ def test_url_incorrect_case_file_index(script, data): ) # only Upper-2.0.tar.gz should get installed. - egg_folder = script.site_packages / 'Dinner-1.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Dinner-1.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder not in result.files_created, str(result) - egg_folder = script.site_packages / 'Dinner-2.0-py%s.egg-info' % pyversion + egg_folder = script.site_packages / \ + 'Dinner-2.0-py{pyversion}.egg-info'.format(**globals()) assert egg_folder in result.files_created, str(result) # Should show index-url location in output @@ -1258,7 +1297,7 @@ def test_install_subprocess_output_handling(script, data): def test_install_log(script, data, tmpdir): # test that verbose logs go to "--log" file f = tmpdir.joinpath("log.txt") - args = ['--log=%s' % f, + args = ['--log={f}'.format(**locals()), 'install', data.src.joinpath('chattymodule')] result = script.pip(*args) assert 0 == result.stdout.count("HELLO FROM CHATTYMODULE") @@ -1411,7 +1450,8 @@ def test_install_editable_with_wrong_egg_name(script): version='0.1') """)) result = script.pip( - 'install', '--editable', 'file://%s#egg=pkgb' % pkga_path + 'install', '--editable', + 'file://{pkga_path}#egg=pkgb'.format(**locals()), ) assert ("Generating metadata for package pkgb produced metadata " "for project name pkga. Fix your #egg=pkgb " @@ -1485,7 +1525,9 @@ def test_install_incompatible_python_requires_editable(script): version='0.1') """)) result = script.pip( - 'install', '--editable=%s' % pkga_path, expect_error=True) + 'install', + '--editable={pkga_path}'.format(**locals()), + expect_error=True) assert _get_expected_error_text() in result.stderr, str(result) @@ -1599,7 +1641,7 @@ def test_installed_files_recorded_in_deterministic_order(script, data): to_install = data.packages.joinpath("FSPkg") result = script.pip('install', to_install) fspkg_folder = script.site_packages / 'fspkg' - egg_info = 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion + egg_info = 'FSPkg-0.1.dev0-py{pyversion}.egg-info'.format(**globals()) installed_files_path = ( script.site_packages / egg_info / 'installed-files.txt' ) @@ -1664,8 +1706,8 @@ def test_target_install_ignores_distutils_config_install_prefix(script): distutils_config.write_text(textwrap.dedent( ''' [install] - prefix=%s - ''' % str(prefix))) + prefix={prefix} + '''.format(**locals()))) target = script.scratch_path / 'target' result = script.pip_install_local('simplewheel', '-t', target) diff --git a/tests/functional/test_install_cleanup.py b/tests/functional/test_install_cleanup.py index b07c80907..131caf681 100644 --- a/tests/functional/test_install_cleanup.py +++ b/tests/functional/test_install_cleanup.py @@ -85,7 +85,8 @@ def test_cleanup_req_satisfied_no_name(script, data): script.pip('install', dist) build = script.venv_path / 'build' - assert not exists(build), "unexpected build/ dir exists: %s" % build + assert not exists(build), \ + "unexpected build/ dir exists: {build}".format(**locals()) script.assert_no_temp() @@ -99,7 +100,8 @@ def test_cleanup_after_install_exception(script, data): expect_error=True, ) build = script.venv_path / 'build' - assert not exists(build), "build/ dir still exists: %s" % result.stdout + assert not exists(build), \ + "build/ dir still exists: {result.stdout}".format(**locals()) script.assert_no_temp() @@ -113,7 +115,8 @@ def test_cleanup_after_egg_info_exception(script, data): expect_error=True, ) build = script.venv_path / 'build' - assert not exists(build), "build/ dir still exists: %s" % result.stdout + assert not exists(build), \ + "build/ dir still exists: {result.stdout}".format(**locals()) script.assert_no_temp() diff --git a/tests/functional/test_install_compat.py b/tests/functional/test_install_compat.py index b957934ef..60d505188 100644 --- a/tests/functional/test_install_compat.py +++ b/tests/functional/test_install_compat.py @@ -6,7 +6,8 @@ import os import pytest -from tests.lib import assert_all_changes, pyversion +from tests.lib import pyversion # noqa: F401 +from tests.lib import assert_all_changes @pytest.mark.network @@ -24,17 +25,20 @@ def test_debian_egg_name_workaround(script): result = script.pip('install', 'INITools==0.2') egg_info = os.path.join( - script.site_packages, "INITools-0.2-py%s.egg-info" % pyversion) + script.site_packages, + "INITools-0.2-py{pyversion}.egg-info".format(**globals())) # Debian only removes pyversion for global installs, not inside a venv # so even if this test runs on a Debian/Ubuntu system with broken # setuptools, since our test runs inside a venv we'll still have the normal # .egg-info - assert egg_info in result.files_created, "Couldn't find %s" % egg_info + assert egg_info in result.files_created, \ + "Couldn't find {egg_info}".format(**locals()) # The Debian no-pyversion version of the .egg-info mangled = os.path.join(script.site_packages, "INITools-0.2.egg-info") - assert mangled not in result.files_created, "Found unexpected %s" % mangled + assert mangled not in result.files_created, \ + "Found unexpected {mangled}".format(**locals()) # Simulate a Debian install by copying the .egg-info to their name for it full_egg_info = os.path.join(script.base_path, egg_info) diff --git a/tests/functional/test_install_config.py b/tests/functional/test_install_config.py index 2b76e81cd..088016a9f 100644 --- a/tests/functional/test_install_config.py +++ b/tests/functional/test_install_config.py @@ -107,7 +107,7 @@ def test_command_line_appends_correctly(script, data): """ script.environ['PIP_FIND_LINKS'] = ( - 'https://test.pypi.org %s' % data.find_links + 'https://test.pypi.org {data.find_links}'.format(**locals()) ) result = script.pip( 'install', '-vvv', 'INITools', '--trusted-host', diff --git a/tests/functional/test_install_extras.py b/tests/functional/test_install_extras.py index acfd58dff..bce95cb19 100644 --- a/tests/functional/test_install_extras.py +++ b/tests/functional/test_install_extras.py @@ -121,7 +121,7 @@ def test_install_special_extra(script): """)) result = script.pip( - 'install', '--no-index', '%s[Hop_hOp-hoP]' % pkga_path, + 'install', '--no-index', '{pkga_path}[Hop_hOp-hoP]'.format(**locals()), expect_error=True) assert ( "Could not find a version that satisfies the requirement missing_pkg" diff --git a/tests/functional/test_install_reqs.py b/tests/functional/test_install_reqs.py index 2422bdb50..0c00060a2 100644 --- a/tests/functional/test_install_reqs.py +++ b/tests/functional/test_install_reqs.py @@ -24,14 +24,14 @@ def test_requirements_file(script): script.scratch_path.joinpath("initools-req.txt").write_text(textwrap.dedent("""\ INITools==0.2 # and something else to test out: - %s<=%s - """ % (other_lib_name, other_lib_version))) + {other_lib_name}<={other_lib_version} + """.format(**locals()))) result = script.pip( 'install', '-r', script.scratch_path / 'initools-req.txt' ) assert ( script.site_packages / 'INITools-0.2-py{}.egg-info'.format( - pyversion in result.files_created) + pyversion) in result.files_created ) assert script.site_packages / 'initools' in result.files_created assert result.files_created[script.site_packages / other_lib_name].dir @@ -46,7 +46,7 @@ def test_schema_check_in_requirements_file(script): """ script.scratch_path.joinpath("file-egg-req.txt").write_text( - "\n%s\n" % ( + "\n{}\n".format( "git://github.com/alex/django-fixture-generator.git" "#egg=fixture_generator" ) @@ -73,7 +73,8 @@ def test_relative_requirements_file(script, data, test_type, editable): """ egg_info_file = ( - script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion + script.site_packages / + 'FSPkg-0.1.dev0-py{pyversion}.egg-info'.format(**globals()) ) egg_link_file = ( script.site_packages / 'FSPkg.egg-link' @@ -120,22 +121,24 @@ def test_multiple_requirements_files(script, tmpdir): other_lib_name, other_lib_version = 'anyjson', '0.3' script.scratch_path.joinpath("initools-req.txt").write_text( textwrap.dedent(""" - -e %s@10#egg=INITools - -r %s-req.txt - """) % + -e {}@10#egg=INITools + -r {}-req.txt + """).format ( local_checkout('svn+http://svn.colorstudy.com/INITools', tmpdir), other_lib_name ), ) - script.scratch_path.joinpath("%s-req.txt" % other_lib_name).write_text( - "%s<=%s" % (other_lib_name, other_lib_version) + script.scratch_path.joinpath( + "{other_lib_name}-req.txt".format(**locals())).write_text( + "{other_lib_name}<={other_lib_version}".format(**locals()) ) result = script.pip( 'install', '-r', script.scratch_path / 'initools-req.txt' ) assert result.files_created[script.site_packages / other_lib_name].dir - fn = '%s-%s-py%s.egg-info' % (other_lib_name, other_lib_version, pyversion) + fn = '{other_lib_name}-{other_lib_version}-py{pyversion}.egg-info'.format( + pyversion=pyversion, **locals()) assert result.files_created[script.site_packages / fn].dir assert script.venv / 'src' / 'initools' in result.files_created @@ -176,13 +179,13 @@ def test_respect_order_in_requirements_file(script, data): if 'Processing' in line] assert 'parent' in downloaded[0], ( - 'First download should be "parent" but was "%s"' % downloaded[0] + 'First download should be "parent" but was "{}"'.format(downloaded[0]) ) assert 'child' in downloaded[1], ( - 'Second download should be "child" but was "%s"' % downloaded[1] + 'Second download should be "child" but was "{}"'.format(downloaded[1]) ) assert 'simple' in downloaded[2], ( - 'Third download should be "simple" but was "%s"' % downloaded[2] + 'Third download should be "simple" but was "{}"'.format(downloaded[2]) ) @@ -215,8 +218,9 @@ def test_install_local_editable_with_subdirectory(script): 'version_subdir') result = script.pip( 'install', '-e', - '%s#egg=version_subpkg&subdirectory=version_subdir' % - ('git+%s' % path_to_url(version_pkg_path),) + '{uri}#egg=version_subpkg&subdirectory=version_subdir'.format( + uri='git+' + path_to_url(version_pkg_path), + ), ) result.assert_installed('version-subpkg', sub_dir='version_subdir') @@ -228,8 +232,9 @@ def test_install_local_with_subdirectory(script): 'version_subdir') result = script.pip( 'install', - '%s#egg=version_subpkg&subdirectory=version_subdir' % - ('git+' + path_to_url(version_pkg_path),) + '{uri}#egg=version_subpkg&subdirectory=version_subdir'.format( + uri='git+' + path_to_url(version_pkg_path), + ), ) result.assert_installed('version_subpkg.py', editable=False) @@ -247,7 +252,7 @@ def test_wheel_user_with_prefix_in_pydistutils_cfg( with open(user_cfg, "w") as cfg: cfg.write(textwrap.dedent(""" [install] - prefix=%s""" % script.scratch_path)) + prefix={script.scratch_path}""".format(**locals()))) result = script.pip( 'install', '--user', '--no-index', @@ -268,13 +273,14 @@ def test_install_option_in_requirements_file(script, data, virtualenv): script.scratch_path.joinpath("reqs.txt").write_text( textwrap.dedent( - """simple --install-option='--home=%s'""" - % script.scratch_path.joinpath("home1"))) + """simple --install-option='--home={home}'""".format( + home=script.scratch_path.joinpath("home1")))) result = script.pip( 'install', '--no-index', '-f', data.find_links, '-r', script.scratch_path / 'reqs.txt', - '--install-option=--home=%s' % script.scratch_path.joinpath("home2"), + '--install-option=--home={home}'.format( + home=script.scratch_path.joinpath("home2")), expect_stderr=True) package_dir = script.scratch / 'home1' / 'lib' / 'python' / 'simple' @@ -333,7 +339,7 @@ def test_constraints_local_install_causes_error(script, data): def test_constraints_constrain_to_local_editable(script, data): to_install = data.src.joinpath("singlemodule") script.scratch_path.joinpath("constraints.txt").write_text( - "-e %s#egg=singlemodule" % path_to_url(to_install) + "-e {url}#egg=singlemodule".format(url=path_to_url(to_install)) ) result = script.pip( 'install', '--no-index', '-f', data.find_links, '-c', @@ -344,7 +350,7 @@ def test_constraints_constrain_to_local_editable(script, data): def test_constraints_constrain_to_local(script, data): to_install = data.src.joinpath("singlemodule") script.scratch_path.joinpath("constraints.txt").write_text( - "%s#egg=singlemodule" % path_to_url(to_install) + "{url}#egg=singlemodule".format(url=path_to_url(to_install)) ) result = script.pip( 'install', '--no-index', '-f', data.find_links, '-c', @@ -400,7 +406,7 @@ def test_double_install_spurious_hash_mismatch( def test_install_with_extras_from_constraints(script, data): to_install = data.packages.joinpath("LocalExtras") script.scratch_path.joinpath("constraints.txt").write_text( - "%s#egg=LocalExtras[bar]" % path_to_url(to_install) + "{url}#egg=LocalExtras[bar]".format(url=path_to_url(to_install)) ) result = script.pip_install_local( '-c', script.scratch_path / 'constraints.txt', 'LocalExtras') @@ -410,7 +416,7 @@ def test_install_with_extras_from_constraints(script, data): def test_install_with_extras_from_install(script, data): to_install = data.packages.joinpath("LocalExtras") script.scratch_path.joinpath("constraints.txt").write_text( - "%s#egg=LocalExtras" % path_to_url(to_install) + "{url}#egg=LocalExtras".format(url=path_to_url(to_install)) ) result = script.pip_install_local( '-c', script.scratch_path / 'constraints.txt', 'LocalExtras[baz]') @@ -420,7 +426,7 @@ def test_install_with_extras_from_install(script, data): def test_install_with_extras_joined(script, data): to_install = data.packages.joinpath("LocalExtras") script.scratch_path.joinpath("constraints.txt").write_text( - "%s#egg=LocalExtras[bar]" % path_to_url(to_install) + "{url}#egg=LocalExtras[bar]".format(url=path_to_url(to_install)) ) result = script.pip_install_local( '-c', script.scratch_path / 'constraints.txt', 'LocalExtras[baz]' @@ -432,7 +438,7 @@ def test_install_with_extras_joined(script, data): def test_install_with_extras_editable_joined(script, data): to_install = data.packages.joinpath("LocalExtras") script.scratch_path.joinpath("constraints.txt").write_text( - "-e %s#egg=LocalExtras[bar]" % path_to_url(to_install) + "-e {url}#egg=LocalExtras[bar]".format(url=path_to_url(to_install)) ) result = script.pip_install_local( '-c', script.scratch_path / 'constraints.txt', 'LocalExtras[baz]') @@ -454,13 +460,15 @@ def test_install_distribution_duplicate_extras(script, data): package_name = to_install + "[bar]" with pytest.raises(AssertionError): result = script.pip_install_local(package_name, package_name) - assert 'Double requirement given: %s' % package_name in result.stderr + expected = ( + 'Double requirement given: {package_name}'.format(**locals())) + assert expected in result.stderr def test_install_distribution_union_with_constraints(script, data): to_install = data.packages.joinpath("LocalExtras") script.scratch_path.joinpath("constraints.txt").write_text( - "%s[bar]" % to_install) + "{to_install}[bar]".format(**locals())) result = script.pip_install_local( '-c', script.scratch_path / 'constraints.txt', to_install + '[baz]') assert 'Running setup.py install for LocalExtras' in result.stdout @@ -492,11 +500,10 @@ def test_install_distribution_union_conflicting_extras(script, data): def test_install_unsupported_wheel_link_with_marker(script): script.scratch_path.joinpath("with-marker.txt").write_text( textwrap.dedent("""\ - %s; %s - """) % - ( - 'https://github.com/a/b/c/asdf-1.5.2-cp27-none-xyz.whl', - 'sys_platform == "xyz"' + {url}; {req} + """).format( + url='https://github.com/a/b/c/asdf-1.5.2-cp27-none-xyz.whl', + req='sys_platform == "xyz"', ) ) result = script.pip( @@ -511,9 +518,10 @@ def test_install_unsupported_wheel_link_with_marker(script): def test_install_unsupported_wheel_file(script, data): # Trying to install a local wheel with an incompatible version/type # should fail. + path = data.packages.joinpath("simple.dist-0.1-py1-none-invalid.whl") script.scratch_path.joinpath("wheel-file.txt").write_text(textwrap.dedent("""\ - %s - """ % data.packages.joinpath("simple.dist-0.1-py1-none-invalid.whl"))) + {path} + """.format(**locals()))) result = script.pip( 'install', '-r', script.scratch_path / 'wheel-file.txt', expect_error=True, @@ -538,9 +546,9 @@ def test_install_options_local_to_package(script, data): reqs_file = script.scratch_path.joinpath("reqs.txt") reqs_file.write_text( textwrap.dedent(""" - simple --install-option='--home=%s' + simple --install-option='--home={home_simple}' INITools - """ % home_simple)) + """.format(**locals()))) result = script.pip( 'install', '--no-index', '-f', data.find_links, diff --git a/tests/functional/test_install_upgrade.py b/tests/functional/test_install_upgrade.py index 0024de4d4..f5445a0b3 100644 --- a/tests/functional/test_install_upgrade.py +++ b/tests/functional/test_install_upgrade.py @@ -4,7 +4,8 @@ import textwrap import pytest -from tests.lib import assert_all_changes, pyversion +from tests.lib import pyversion # noqa: F401 +from tests.lib import assert_all_changes from tests.lib.local_repos import local_checkout @@ -46,11 +47,13 @@ def test_only_if_needed_does_not_upgrade_deps_when_satisfied(script): ) assert ( - (script.site_packages / 'require_simple-1.0-py%s.egg-info' % pyversion) + (script.site_packages / 'require_simple-1.0-py{pyversion}.egg-info' + .format(**globals())) not in result.files_deleted ), "should have installed require_simple==1.0" assert ( - (script.site_packages / 'simple-2.0-py%s.egg-info' % pyversion) + (script.site_packages / 'simple-2.0-py{pyversion}.egg-info' + .format(**globals())) not in result.files_deleted ), "should not have uninstalled simple==2.0" assert ( @@ -70,16 +73,23 @@ def test_only_if_needed_does_upgrade_deps_when_no_longer_satisfied(script): ) assert ( - (script.site_packages / 'require_simple-1.0-py%s.egg-info' % pyversion) + (script.site_packages / 'require_simple-1.0-py{pyversion}.egg-info' + .format(**globals())) not in result.files_deleted ), "should have installed require_simple==1.0" + expected = ( + script.site_packages / + 'simple-3.0-py{pyversion}.egg-info'.format(**globals()) + ) assert ( - script.site_packages / 'simple-3.0-py%s.egg-info' % - pyversion in result.files_created + expected in result.files_created ), "should have installed simple==3.0" + expected = ( + script.site_packages / + 'simple-1.0-py{pyversion}.egg-info'.format(**globals()) + ) assert ( - script.site_packages / 'simple-1.0-py%s.egg-info' % - pyversion in result.files_deleted + expected in result.files_deleted ), "should have uninstalled simple==1.0" @@ -94,11 +104,13 @@ def test_eager_does_upgrade_dependecies_when_currently_satisfied(script): ) assert ( - (script.site_packages / 'require_simple-1.0-py%s.egg-info' % pyversion) + (script.site_packages / + 'require_simple-1.0-py{pyversion}.egg-info'.format(**globals())) not in result.files_deleted ), "should have installed require_simple==1.0" assert ( - (script.site_packages / 'simple-2.0-py%s.egg-info' % pyversion) + (script.site_packages / + 'simple-2.0-py{pyversion}.egg-info'.format(**globals())) in result.files_deleted ), "should have uninstalled simple==2.0" @@ -114,16 +126,19 @@ def test_eager_does_upgrade_dependecies_when_no_longer_satisfied(script): ) assert ( - (script.site_packages / 'require_simple-1.0-py%s.egg-info' % pyversion) + (script.site_packages / + 'require_simple-1.0-py{pyversion}.egg-info'.format(**globals())) not in result.files_deleted ), "should have installed require_simple==1.0" assert ( - script.site_packages / 'simple-3.0-py%s.egg-info' % - pyversion in result.files_created + script.site_packages / + 'simple-3.0-py{pyversion}.egg-info'.format(**globals()) + in result.files_created ), "should have installed simple==3.0" assert ( - script.site_packages / 'simple-1.0-py%s.egg-info' % - pyversion in result.files_deleted + script.site_packages / + 'simple-1.0-py{pyversion}.egg-info'.format(**globals()) + in result.files_deleted ), "should have uninstalled simple==1.0" @@ -139,12 +154,14 @@ def test_upgrade_to_specific_version(script): 'pip install with specific version did not upgrade' ) assert ( - script.site_packages / 'INITools-0.1-py%s.egg-info' % - pyversion in result.files_deleted + script.site_packages / 'INITools-0.1-py{pyversion}.egg-info' + .format(**globals()) + in result.files_deleted ) assert ( - script.site_packages / 'INITools-0.2-py%s.egg-info' % - pyversion in result.files_created + script.site_packages / 'INITools-0.2-py{pyversion}.egg-info' + .format(**globals()) + in result.files_created ) @@ -158,8 +175,9 @@ def test_upgrade_if_requested(script): result = script.pip('install', '--upgrade', 'INITools') assert result.files_created, 'pip install --upgrade did not upgrade' assert ( - script.site_packages / 'INITools-0.1-py%s.egg-info' % - pyversion not in result.files_created + script.site_packages / + 'INITools-0.1-py{pyversion}.egg-info'.format(**globals()) + not in result.files_created ) @@ -322,12 +340,14 @@ def test_should_not_install_always_from_cache(script): script.pip('uninstall', '-y', 'INITools') result = script.pip('install', 'INITools==0.1') assert ( - script.site_packages / 'INITools-0.2-py%s.egg-info' % - pyversion not in result.files_created + script.site_packages / + 'INITools-0.2-py{pyversion}.egg-info'.format(**globals()) + not in result.files_created ) assert ( - script.site_packages / 'INITools-0.1-py%s.egg-info' % - pyversion in result.files_created + script.site_packages / + 'INITools-0.1-py{pyversion}.egg-info'.format(**globals()) + in result.files_created ) @@ -341,18 +361,22 @@ def test_install_with_ignoreinstalled_requested(script): assert result.files_created, 'pip install -I did not install' # both the old and new metadata should be present. assert os.path.exists( - script.site_packages_path / 'INITools-0.1-py%s.egg-info' % pyversion + script.site_packages_path / + 'INITools-0.1-py{pyversion}.egg-info'.format(**globals()) ) assert os.path.exists( - script.site_packages_path / 'INITools-0.3-py%s.egg-info' % pyversion + script.site_packages_path / + 'INITools-0.3-py{pyversion}.egg-info'.format(**globals()) ) @pytest.mark.network def test_upgrade_vcs_req_with_no_dists_found(script, tmpdir): """It can upgrade a VCS requirement that has no distributions otherwise.""" - req = "%s#egg=pip-test-package" % local_checkout( - "git+https://github.com/pypa/pip-test-package.git", tmpdir, + req = "{checkout}#egg=pip-test-package".format( + checkout=local_checkout( + "git+https://github.com/pypa/pip-test-package.git", tmpdir, + ) ) script.pip("install", req) result = script.pip("install", "-U", req) @@ -365,10 +389,11 @@ def test_upgrade_vcs_req_with_dist_found(script): # TODO(pnasrat) Using local_checkout fails on windows - oddness with the # test path urls/git. req = ( - "%s#egg=pretend" % - ( - "git+git://github.com/alex/pretend@e7f26ad7dbcb4a02a4995aade4" - "743aad47656b27" + "{url}#egg=pretend".format( + url=( + "git+git://github.com/alex/pretend@e7f26ad7dbcb4a02a4995aade4" + "743aad47656b27" + ), ) ) script.pip("install", req, expect_stderr=True) @@ -401,7 +426,8 @@ class TestUpgradeDistributeToSetuptools(object): def prep_ve(self, script, version, pip_src, distribute=False): self.script = script - self.script.pip_install_local('virtualenv==%s' % version) + self.script.pip_install_local( + 'virtualenv=={version}'.format(**locals())) args = ['virtualenv', self.script.scratch_path / 'VE'] if distribute: args.insert(1, '--distribute') diff --git a/tests/functional/test_install_user.py b/tests/functional/test_install_user.py index 2cc91f56c..09dbdf491 100644 --- a/tests/functional/test_install_user.py +++ b/tests/functional/test_install_user.py @@ -6,7 +6,8 @@ from os.path import curdir, isdir, isfile import pytest -from tests.lib import need_svn, pyversion +from tests.lib import pyversion # noqa: F401 +from tests.lib import need_svn from tests.lib.local_repos import local_checkout @@ -52,8 +53,10 @@ class Tests_UserSite: """ result = script.pip( 'install', '--user', '-e', - '%s#egg=initools' % - local_checkout('svn+http://svn.colorstudy.com/INITools', tmpdir) + '{checkout}#egg=initools'.format( + checkout=local_checkout( + 'svn+http://svn.colorstudy.com/INITools', tmpdir) + ) ) result.assert_installed('INITools', use_user_site=True) @@ -110,7 +113,8 @@ class Tests_UserSite: # usersite has 0.1 egg_info_folder = ( - script.user_site / 'INITools-0.1-py%s.egg-info' % pyversion + script.user_site / + 'INITools-0.1-py{pyversion}.egg-info'.format(**globals()) ) initools_v3_file = ( # file only in 0.3 @@ -136,7 +140,8 @@ class Tests_UserSite: # usersite has 0.1 egg_info_folder = ( - script.user_site / 'INITools-0.1-py%s.egg-info' % pyversion + script.user_site / + 'INITools-0.1-py{pyversion}.egg-info'.format(**globals()) ) initools_folder = script.user_site / 'initools' assert egg_info_folder in result2.files_created, str(result2) @@ -145,7 +150,7 @@ class Tests_UserSite: # site still has 0.2 (can't look in result1; have to check) egg_info_folder = ( script.base_path / script.site_packages / - 'INITools-0.2-py%s.egg-info' % pyversion + 'INITools-0.2-py{pyversion}.egg-info'.format(**globals()) ) initools_folder = script.base_path / script.site_packages / 'initools' assert isdir(egg_info_folder) @@ -166,7 +171,8 @@ class Tests_UserSite: # usersite has 0.3.1 egg_info_folder = ( - script.user_site / 'INITools-0.3.1-py%s.egg-info' % pyversion + script.user_site / + 'INITools-0.3.1-py{pyversion}.egg-info'.format(**globals()) ) initools_folder = script.user_site / 'initools' assert egg_info_folder in result2.files_created, str(result2) @@ -175,7 +181,7 @@ class Tests_UserSite: # site still has 0.2 (can't look in result1; have to check) egg_info_folder = ( script.base_path / script.site_packages / - 'INITools-0.2-py%s.egg-info' % pyversion + 'INITools-0.2-py{pyversion}.egg-info'.format(**globals()) ) initools_folder = script.base_path / script.site_packages / 'initools' assert isdir(egg_info_folder), result2.stdout @@ -199,7 +205,8 @@ class Tests_UserSite: # usersite has 0.1 egg_info_folder = ( - script.user_site / 'INITools-0.1-py%s.egg-info' % pyversion + script.user_site / + 'INITools-0.1-py{pyversion}.egg-info'.format(**globals()) ) initools_v3_file = ( # file only in 0.3 @@ -212,7 +219,7 @@ class Tests_UserSite: # site still has 0.2 (can't just look in result1; have to check) egg_info_folder = ( script.base_path / script.site_packages / - 'INITools-0.2-py%s.egg-info' % pyversion + 'INITools-0.2-py{pyversion}.egg-info'.format(**globals()) ) initools_folder = script.base_path / script.site_packages / 'initools' assert isdir(egg_info_folder) @@ -241,6 +248,9 @@ class Tests_UserSite: dist_location = resultp.stdout.strip() assert ( "Will not install to the user site because it will lack sys.path " - "precedence to %s in %s" % - ('INITools', dist_location) in result2.stderr + "precedence to {name} in {location}".format( + name='INITools', + location=dist_location, + ) + in result2.stderr ) diff --git a/tests/functional/test_install_vcs_git.py b/tests/functional/test_install_vcs_git.py index 01fec7a8b..6c6f5a0c7 100644 --- a/tests/functional/test_install_vcs_git.py +++ b/tests/functional/test_install_vcs_git.py @@ -1,10 +1,10 @@ import pytest +from tests.lib import pyversion # noqa: F401 from tests.lib import ( _change_test_package_version, _create_test_package, _test_path_to_file_url, - pyversion, ) from tests.lib.git_submodule_helpers import ( _change_test_package_submodule, @@ -171,7 +171,7 @@ def test_install_noneditable_git(script, tmpdir): ) egg_info_folder = ( script.site_packages / - 'pip_test_package-0.1.1-py%s.egg-info' % pyversion + 'pip_test_package-0.1.1-py{pyversion}.egg-info'.format(**globals()) ) result.assert_installed('piptestpackage', without_egg_link=True, diff --git a/tests/functional/test_pep517.py b/tests/functional/test_pep517.py index d932f2ef8..0286fe1f0 100644 --- a/tests/functional/test_pep517.py +++ b/tests/functional/test_pep517.py @@ -134,11 +134,13 @@ def test_conflicting_pep517_backend_requirements(script, tmpdir, data): project_dir, expect_error=True ) + msg = ( + 'Some build dependencies for {url} conflict with the backend ' + 'dependencies: simplewheel==1.0 is incompatible with ' + 'simplewheel==2.0.'.format(url=path_to_url(project_dir))) assert ( result.returncode != 0 and - ('Some build dependencies for %s conflict with the backend ' - 'dependencies: simplewheel==1.0 is incompatible with ' - 'simplewheel==2.0.' % path_to_url(project_dir)) in result.stderr + msg in result.stderr ), str(result) diff --git a/tests/functional/test_uninstall.py b/tests/functional/test_uninstall.py index e06ff0246..04d8550f3 100644 --- a/tests/functional/test_uninstall.py +++ b/tests/functional/test_uninstall.py @@ -328,8 +328,9 @@ def test_uninstall_editable_from_svn(script, tmpdir): """ result = script.pip( 'install', '-e', - '%s#egg=initools' % ( - local_checkout('svn+http://svn.colorstudy.com/INITools', tmpdir) + '{checkout}#egg=initools'.format( + checkout=local_checkout( + 'svn+http://svn.colorstudy.com/INITools', tmpdir) ), ) result.assert_installed('INITools') @@ -396,10 +397,10 @@ def test_uninstall_from_reqs_file(script, tmpdir): ) script.scratch_path.joinpath("test-req.txt").write_text( textwrap.dedent(""" - -e %s#egg=initools + -e {url}#egg=initools # and something else to test out: PyLogo<0.4 - """) % local_svn_url + """).format(url=local_svn_url) ) result = script.pip('install', '-r', 'test-req.txt') script.scratch_path.joinpath("test-req.txt").write_text( @@ -409,10 +410,10 @@ def test_uninstall_from_reqs_file(script, tmpdir): -i http://www.example.com --extra-index-url http://www.example.com - -e %s#egg=initools + -e {url}#egg=initools # and something else to test out: PyLogo<0.4 - """) % local_svn_url + """).format(url=local_svn_url) ) result2 = script.pip('uninstall', '-r', 'test-req.txt', '-y') assert_all_changes( diff --git a/tests/functional/test_uninstall_user.py b/tests/functional/test_uninstall_user.py index ed277739a..df635ccf8 100644 --- a/tests/functional/test_uninstall_user.py +++ b/tests/functional/test_uninstall_user.py @@ -6,7 +6,8 @@ from os.path import isdir, isfile, normcase import pytest from tests.functional.test_install_user import _patch_dist_in_site_packages -from tests.lib import assert_all_changes, pyversion +from tests.lib import pyversion # noqa: F401 +from tests.lib import assert_all_changes @pytest.mark.incompatible_with_test_venv @@ -44,7 +45,7 @@ class Tests_UninstallUserSite: # site still has 0.2 (can't look in result1; have to check) egg_info_folder = ( script.base_path / script.site_packages / - 'pip_test_package-0.1-py%s.egg-info' % pyversion + 'pip_test_package-0.1-py{pyversion}.egg-info'.format(**globals()) ) assert isdir(egg_info_folder) diff --git a/tests/functional/test_wheel.py b/tests/functional/test_wheel.py index 181ca0584..ce79dbee5 100644 --- a/tests/functional/test_wheel.py +++ b/tests/functional/test_wheel.py @@ -6,7 +6,7 @@ from os.path import exists import pytest from pip._internal.cli.status_codes import ERROR, PREVIOUS_BUILD_DIR_ERROR -from tests.lib import pyversion +from tests.lib import pyversion # noqa: F401 @pytest.fixture(autouse=True) @@ -48,12 +48,13 @@ def test_pip_wheel_success(script, data): 'wheel', '--no-index', '-f', data.find_links, 'simple==3.0', ) - wheel_file_name = 'simple-3.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'simple-3.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert re.search( r"Created wheel for simple: " - r"filename=%s size=\d+ sha256=[A-Fa-f0-9]{64}" - % re.escape(wheel_file_name), result.stdout) + r"filename={filename} size=\d+ sha256=[A-Fa-f0-9]{{64}}" + .format(filename=re.escape(wheel_file_name)), result.stdout) assert re.search( r"^\s+Stored in directory: ", result.stdout, re.M) assert wheel_file_path in result.files_created, result.stdout @@ -68,7 +69,8 @@ def test_pip_wheel_build_cache(script, data): 'wheel', '--no-index', '-f', data.find_links, 'simple==3.0', ) - wheel_file_name = 'simple-3.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'simple-3.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout assert "Successfully built simple" in result.stdout, result.stdout @@ -145,7 +147,8 @@ def test_pip_wheel_builds_editable_deps(script, data): 'wheel', '--no-index', '-f', data.find_links, '-e', editable_path ) - wheel_file_name = 'simple-1.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'simple-1.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout @@ -159,7 +162,8 @@ def test_pip_wheel_builds_editable(script, data): 'wheel', '--no-index', '-f', data.find_links, '-e', editable_path ) - wheel_file_name = 'simplewheel-1.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'simplewheel-1.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout @@ -173,7 +177,8 @@ def test_pip_wheel_fail(script, data): 'wheelbroken==0.1', expect_error=True, ) - wheel_file_name = 'wheelbroken-0.1-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'wheelbroken-0.1-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path not in result.files_created, ( wheel_file_path, @@ -191,12 +196,13 @@ def test_no_clean_option_blocks_cleaning_after_wheel(script, data): build = script.venv_path / 'build' result = script.pip( 'wheel', '--no-clean', '--no-index', '--build', build, - '--find-links=%s' % data.find_links, + '--find-links={data.find_links}'.format(**locals()), 'simple', expect_temp=True, ) build = build / 'simple' - assert exists(build), "build/simple should still exist %s" % str(result) + assert exists(build), \ + "build/simple should still exist {result}".format(**locals()) def test_pip_wheel_source_deps(script, data): @@ -209,7 +215,8 @@ def test_pip_wheel_source_deps(script, data): 'wheel', '--no-index', '-f', data.find_links, 'requires_source', ) - wheel_file_name = 'source-1.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'source-1.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout assert "Successfully built source" in result.stdout, result.stdout @@ -228,7 +235,8 @@ def test_pip_wheel_fail_cause_of_previous_build_dir(script, data): # When I call pip trying to install things again result = script.pip( - 'wheel', '--no-index', '--find-links=%s' % data.find_links, + 'wheel', '--no-index', + '--find-links={data.find_links}'.format(**locals()), '--build', script.venv_path / 'build', 'simple==3.0', expect_error=True, expect_temp=True, ) @@ -248,7 +256,8 @@ def test_wheel_package_with_latin1_setup(script, data): def test_pip_wheel_with_pep518_build_reqs(script, data, common_wheels): result = script.pip('wheel', '--no-index', '-f', data.find_links, '-f', common_wheels, 'pep518==3.0',) - wheel_file_name = 'pep518-3.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'pep518-3.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout assert "Successfully built pep518" in result.stdout, result.stdout @@ -261,7 +270,8 @@ def test_pip_wheel_with_pep518_build_reqs_no_isolation(script, data): 'wheel', '--no-index', '-f', data.find_links, '--no-build-isolation', 'pep518==3.0', ) - wheel_file_name = 'pep518-3.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'pep518-3.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout assert "Successfully built pep518" in result.stdout, result.stdout @@ -289,7 +299,8 @@ def test_pep517_wheels_are_not_confused_with_other_files(script, tmpdir, data): result = script.pip('wheel', pkg_to_wheel, '-w', script.scratch_path) assert "Installing build dependencies" in result.stdout, result.stdout - wheel_file_name = 'withpyproject-0.0.1-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'withpyproject-0.0.1-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout @@ -303,6 +314,7 @@ def test_legacy_wheels_are_not_confused_with_other_files(script, tmpdir, data): result = script.pip('wheel', pkg_to_wheel, '-w', script.scratch_path) assert "Installing build dependencies" not in result.stdout, result.stdout - wheel_file_name = 'simplewheel-1.0-py%s-none-any.whl' % pyversion[0] + wheel_file_name = 'simplewheel-1.0-py{pyversion[0]}-none-any.whl' \ + .format(**globals()) wheel_file_path = script.scratch / wheel_file_name assert wheel_file_path in result.files_created, result.stdout diff --git a/tests/lib/__init__.py b/tests/lib/__init__.py index 272bccdf6..65a239926 100644 --- a/tests/lib/__init__.py +++ b/tests/lib/__init__.py @@ -285,14 +285,16 @@ class TestPipResult(object): if without_egg_link: if egg_link_path in self.files_created: raise TestFailure( - 'unexpected egg link file created: %r\n%s' % - (egg_link_path, self) + 'unexpected egg link file created: ' + '{egg_link_path!r}\n{self}' + .format(**locals()) ) else: if egg_link_path not in self.files_created: raise TestFailure( - 'expected egg link file missing: %r\n%s' % - (egg_link_path, self) + 'expected egg link file missing: ' + '{egg_link_path!r}\n{self}' + .format(**locals()) ) egg_link_file = self.files_created[egg_link_path] @@ -301,15 +303,15 @@ class TestPipResult(object): # FIXME: I don't understand why there's a trailing . here if not (egg_link_contents.endswith('\n.') and egg_link_contents[:-2].endswith(pkg_dir)): - raise TestFailure(textwrap.dedent(u'''\ - Incorrect egg_link file %r - Expected ending: %r + raise TestFailure(textwrap.dedent( + u'''\ + Incorrect egg_link file {egg_link_file!r} + Expected ending: {expected_ending!r} ------- Actual contents ------- - %s - -------------------------------''' % ( - egg_link_file, - pkg_dir + '\n.', - repr(egg_link_contents)) + {egg_link_contents!r} + -------------------------------'''.format( + expected_ending=pkg_dir + '\n.', + **locals()) )) if use_user_site: @@ -318,33 +320,36 @@ class TestPipResult(object): pth_file = e.site_packages / 'easy-install.pth' if (pth_file in self.files_updated) == without_egg_link: - raise TestFailure('%r unexpectedly %supdated by install' % ( - pth_file, (not without_egg_link and 'not ' or ''))) + raise TestFailure( + '{pth_file} unexpectedly {maybe}updated by install'.format( + maybe=not without_egg_link and 'not ' or '', + **locals())) if (pkg_dir in self.files_created) == (curdir in without_files): raise TestFailure(textwrap.dedent('''\ - expected package directory %r %sto be created + expected package directory {pkg_dir!r} {maybe}to be created actually created: - %s - ''') % ( - pkg_dir, - (curdir in without_files and 'not ' or ''), - sorted(self.files_created.keys()))) + {files} + ''').format( + pkg_dir=pkg_dir, + maybe=curdir in without_files and 'not ' or '', + files=sorted(self.files_created.keys()), + )) for f in with_files: normalized_path = os.path.normpath(pkg_dir / f) if normalized_path not in self.files_created: raise TestFailure( - 'Package directory %r missing expected content %r' % - (pkg_dir, f) + 'Package directory {pkg_dir!r} missing ' + 'expected content {f!r}'.format(**locals()) ) for f in without_files: normalized_path = os.path.normpath(pkg_dir / f) if normalized_path in self.files_created: raise TestFailure( - 'Package directory %r has unexpected content %f' % - (pkg_dir, f) + 'Package directory {pkg_dir!r} has unexpected content {f}' + .format(**locals()) ) @@ -487,7 +492,7 @@ class PipTestEnvironment(TestFileEnvironment): # Expand our absolute path directories into relative for name in ["base", "venv", "bin", "lib", "site_packages", "user_base", "user_site", "user_bin", "scratch"]: - real_name = "%s_path" % name + real_name = "{name}_path".format(**locals()) relative_path = Path(os.path.relpath( getattr(self, real_name), self.base_path )) @@ -537,7 +542,7 @@ class PipTestEnvironment(TestFileEnvironment): compatibility. """ if self.verbose: - print('>> running %s %s' % (args, kw)) + print('>> running {args} {kw}'.format(**locals())) cwd = kw.pop('cwd', None) run_from = kw.pop('run_from', None) @@ -791,7 +796,7 @@ def _vcs_add(script, version_pkg_path, vcs='git'): '-m', 'initial version', cwd=version_pkg_path, ) else: - raise ValueError('Unknown vcs: %r' % vcs) + raise ValueError('Unknown vcs: {vcs}'.format(**locals())) return version_pkg_path @@ -900,7 +905,7 @@ def assert_raises_regexp(exception, reg, run, *args, **kwargs): try: run(*args, **kwargs) - assert False, "%s should have been thrown" % exception + assert False, "{exception} should have been thrown".format(**locals()) except exception: e = sys.exc_info()[1] p = re.compile(reg) @@ -928,9 +933,9 @@ def create_test_package_with_setup(script, **setup_kwargs): pkg_path.mkdir() pkg_path.joinpath("setup.py").write_text(textwrap.dedent(""" from setuptools import setup - kwargs = %r + kwargs = {setup_kwargs!r} setup(**kwargs) - """) % setup_kwargs) + """).format(**locals())) return pkg_path @@ -1075,7 +1080,8 @@ def need_executable(name, check_cmd): try: subprocess.check_output(check_cmd) except OSError: - return pytest.mark.skip(reason='%s is not available' % name)(fn) + return pytest.mark.skip( + reason='{name} is not available'.format(name=name))(fn) return fn return wrapper diff --git a/tests/lib/path.py b/tests/lib/path.py index a74e478ec..d1ea6bc5e 100644 --- a/tests/lib/path.py +++ b/tests/lib/path.py @@ -81,7 +81,7 @@ class Path(_base): return Path(path + _base(self)) def __repr__(self): - return u"Path(%s)" % _base.__repr__(self) + return u"Path({inner})".format(inner=_base.__repr__(self)) def __hash__(self): return _base.__hash__(self) diff --git a/tests/lib/test_lib.py b/tests/lib/test_lib.py index 051196032..9c00e9d1f 100644 --- a/tests/lib/test_lib.py +++ b/tests/lib/test_lib.py @@ -65,8 +65,8 @@ def test_correct_pip_version(script): if x.endswith('.py') ] assert not mismatch_py, ( - 'mismatched source files in %r and %r: %r' % - (pip_folder, pip_folder_outputed, mismatch_py) + 'mismatched source files in {pip_folder!r} ' + 'and {pip_folder_outputed!r}: {mismatch_py!r}'.format(**locals()) ) diff --git a/tests/unit/test_build_env.py b/tests/unit/test_build_env.py index b4469046b..1f3b88b4d 100644 --- a/tests/unit/test_build_env.py +++ b/tests/unit/test_build_env.py @@ -33,7 +33,7 @@ def run_with_build_env(script, setup_script_contents, link_collector = LinkCollector( session=PipSession(), - search_scope=SearchScope.create([%r], []), + search_scope=SearchScope.create([{scratch!r}], []), ) selection_prefs = SelectionPreferences( allow_yanked=True, @@ -45,7 +45,7 @@ def run_with_build_env(script, setup_script_contents, with global_tempdir_manager(): build_env = BuildEnvironment() - ''' % str(script.scratch_path)) + + '''.format(scratch=str(script.scratch_path))) + indent(dedent(setup_script_contents), ' ') + indent( dedent( @@ -78,14 +78,17 @@ def test_build_env_allow_only_one_install(script): finder = make_test_finder(find_links=[script.scratch_path]) build_env = BuildEnvironment() for prefix in ('normal', 'overlay'): - build_env.install_requirements(finder, ['foo'], prefix, - 'installing foo in %s' % prefix) + build_env.install_requirements( + finder, ['foo'], prefix, + 'installing foo in {prefix}'.format(**locals())) with pytest.raises(AssertionError): - build_env.install_requirements(finder, ['bar'], prefix, - 'installing bar in %s' % prefix) + build_env.install_requirements( + finder, ['bar'], prefix, + 'installing bar in {prefix}'.format(**locals())) with pytest.raises(AssertionError): - build_env.install_requirements(finder, [], prefix, - 'installing in %s' % prefix) + build_env.install_requirements( + finder, [], prefix, + 'installing in {prefix}'.format(**locals())) def test_build_env_requirements_check(script): @@ -201,7 +204,9 @@ def test_build_env_isolation(script): except ImportError: pass else: - print('imported `pkg` from `%s`' % pkg.__file__, file=sys.stderr) + print( + 'imported `pkg` from `{pkg.__file__}`'.format(**locals()), + file=sys.stderr) print('system sites:\n ' + '\n '.join(sorted({ get_python_lib(plat_specific=0), get_python_lib(plat_specific=1), diff --git a/tests/unit/test_collector.py b/tests/unit/test_collector.py index 1872b046a..a650a2a17 100644 --- a/tests/unit/test_collector.py +++ b/tests/unit/test_collector.py @@ -486,8 +486,8 @@ def test_group_locations__file_expand_dir(data): """ files, urls = group_locations([data.find_links], expand_dir=True) assert files and not urls, ( - "files and not urls should have been found at find-links url: %s" % - data.find_links + "files and not urls should have been found " + "at find-links url: {data.find_links}".format(**locals()) ) diff --git a/tests/unit/test_req.py b/tests/unit/test_req.py index 7e3feaa5c..530c3735c 100644 --- a/tests/unit/test_req.py +++ b/tests/unit/test_req.py @@ -115,8 +115,9 @@ class TestRequirementSet(object): with self._basic_resolver(finder) as resolver: assert_raises_regexp( PreviousBuildDirError, - r"pip can't proceed with [\s\S]*%s[\s\S]*%s" % - (req, build_dir.replace('\\', '\\\\')), + r"pip can't proceed with [\s\S]*{req}[\s\S]*{build_dir_esc}" + .format( + build_dir_esc=build_dir.replace('\\', '\\\\'), req=req), resolver.resolve, reqset.all_requirements, True, @@ -195,7 +196,7 @@ class TestRequirementSet(object): )) dir_path = data.packages.joinpath('FSPkg') reqset.add_requirement(get_processed_req_from_line( - 'file://%s' % (dir_path,), + 'file://{dir_path}'.format(**locals()), lineno=2, )) finder = make_test_finder(find_links=[data.find_links]) @@ -255,7 +256,7 @@ class TestRequirementSet(object): (data.packages / 'simple-1.0.tar.gz').resolve()) reqset = RequirementSet() reqset.add_requirement(get_processed_req_from_line( - '%s --hash=sha256:badbad' % file_url, lineno=1, + '{file_url} --hash=sha256:badbad'.format(**locals()), lineno=1, )) finder = make_test_finder(find_links=[data.find_links]) with self._basic_resolver(finder, require_hashes=True) as resolver: @@ -471,7 +472,7 @@ class TestInstallRequirement(object): # match for markers in ( 'python_version >= "1.0"', - 'sys_platform == %r' % sys.platform, + 'sys_platform == {sys.platform!r}'.format(**globals()), ): line = 'name; ' + markers req = install_req_from_line(line) @@ -481,7 +482,7 @@ class TestInstallRequirement(object): # don't match for markers in ( 'python_version >= "5.0"', - 'sys_platform != %r' % sys.platform, + 'sys_platform != {sys.platform!r}'.format(**globals()), ): line = 'name; ' + markers req = install_req_from_line(line) @@ -492,7 +493,7 @@ class TestInstallRequirement(object): # match for markers in ( 'python_version >= "1.0"', - 'sys_platform == %r' % sys.platform, + 'sys_platform == {sys.platform!r}'.format(**globals()), ): line = 'name; ' + markers req = install_req_from_line(line, comes_from='') @@ -502,7 +503,7 @@ class TestInstallRequirement(object): # don't match for markers in ( 'python_version >= "5.0"', - 'sys_platform != %r' % sys.platform, + 'sys_platform != {sys.platform!r}'.format(**globals()), ): line = 'name; ' + markers req = install_req_from_line(line, comes_from='') diff --git a/tests/unit/test_req_file.py b/tests/unit/test_req_file.py index ea9cebba9..c12cdb64b 100644 --- a/tests/unit/test_req_file.py +++ b/tests/unit/test_req_file.py @@ -1,3 +1,4 @@ +import collections import logging import os import subprocess @@ -304,7 +305,7 @@ class TestProcessLine(object): def test_yield_editable_requirement(self, line_processor): url = 'git+https://url#egg=SomeProject' - line = '-e %s' % url + line = '-e {url}'.format(**locals()) filename = 'filename' comes_from = '-r {} (line {})'.format(filename, 1) req = install_req_from_editable(url, comes_from=comes_from) @@ -625,19 +626,23 @@ class TestParseRequirements(object): def test_expand_existing_env_variables(self, tmpdir, finder): template = ( - 'https://%s:x-oauth-basic@github.com/user/%s/archive/master.zip' + 'https://{}:x-oauth-basic@github.com/' + 'user/{}/archive/master.zip' ) - env_vars = ( + def make_var(name): + return '${{{name}}}'.format(**locals()) + + env_vars = collections.OrderedDict([ ('GITHUB_TOKEN', 'notarealtoken'), ('DO_12_FACTOR', 'awwyeah'), - ) + ]) with open(tmpdir.joinpath('req1.txt'), 'w') as fp: - fp.write(template % tuple(['${%s}' % k for k, _ in env_vars])) + fp.write(template.format(*map(make_var, env_vars))) with patch('pip._internal.req.req_file.os.getenv') as getenv: - getenv.side_effect = lambda n: dict(env_vars)[n] + getenv.side_effect = lambda n: env_vars[n] reqs = list(parse_reqfile( tmpdir.joinpath('req1.txt'), @@ -645,12 +650,12 @@ class TestParseRequirements(object): session=PipSession() )) - assert len(reqs) == 1, \ - 'parsing requirement file with env variable failed' + assert len(reqs) == 1, \ + 'parsing requirement file with env variable failed' - expected_url = template % tuple([v for _, v in env_vars]) - assert reqs[0].link.url == expected_url, \ - 'variable expansion in req file failed' + expected_url = template.format(*env_vars.values()) + assert reqs[0].link.url == expected_url, \ + 'variable expansion in req file failed' def test_expand_missing_env_variables(self, tmpdir, finder): req_url = (