Commit 6b2299c3 by Bjorn Neergaard

feat: pyupgrade via pre-commit

parent 7c53db96
...@@ -40,6 +40,13 @@ repos: ...@@ -40,6 +40,13 @@ repos:
- flake8-typing-imports==1.11.0 - flake8-typing-imports==1.11.0
- pep8-naming==0.12.1 - pep8-naming==0.12.1
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
- id: pyupgrade
args: [--py36-plus]
exclude: '^(install|get)-poetry.py$'
- repo: https://github.com/pycqa/isort - repo: https://github.com/pycqa/isort
rev: 5.10.1 rev: 5.10.1
hooks: hooks:
......
...@@ -247,7 +247,7 @@ class AddCommand(InstallerCommand, InitCommand): ...@@ -247,7 +247,7 @@ class AddCommand(InstallerCommand, InitCommand):
"The following packages are already present in the pyproject.toml and will be skipped:\n" "The following packages are already present in the pyproject.toml and will be skipped:\n"
) )
for name in existing_packages: for name in existing_packages:
self.line(" • <c1>{name}</c1>".format(name=name)) self.line(f" • <c1>{name}</c1>")
self.line( self.line(
"\nIf you want to update it to the latest compatible version, you can use `poetry update package`.\n" "\nIf you want to update it to the latest compatible version, you can use `poetry update package`.\n"
"If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`.\n" "If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`.\n"
......
...@@ -29,7 +29,7 @@ class CacheClearCommand(Command): ...@@ -29,7 +29,7 @@ class CacheClearCommand(Command):
try: try:
cache_dir.relative_to(REPOSITORY_CACHE_DIR) cache_dir.relative_to(REPOSITORY_CACHE_DIR)
except ValueError: except ValueError:
raise ValueError("{} is not a valid repository cache".format(root)) raise ValueError(f"{root} is not a valid repository cache")
cache = CacheManager( cache = CacheManager(
{ {
...@@ -47,7 +47,7 @@ class CacheClearCommand(Command): ...@@ -47,7 +47,7 @@ class CacheClearCommand(Command):
) )
if not os.path.exists(str(cache_dir)): if not os.path.exists(str(cache_dir)):
self.line("No cache entries for {}".format(parts[0])) self.line(f"No cache entries for {parts[0]}")
return 0 return 0
# Calculate number of entries # Calculate number of entries
...@@ -55,9 +55,7 @@ class CacheClearCommand(Command): ...@@ -55,9 +55,7 @@ class CacheClearCommand(Command):
for _path, _dirs, files in os.walk(str(cache_dir)): for _path, _dirs, files in os.walk(str(cache_dir)):
entries_count += len(files) entries_count += len(files)
delete = self.confirm( delete = self.confirm(f"<question>Delete {entries_count} entries?</>")
"<question>Delete {} entries?</>".format(entries_count)
)
if not delete: if not delete:
return 0 return 0
...@@ -71,14 +69,14 @@ class CacheClearCommand(Command): ...@@ -71,14 +69,14 @@ class CacheClearCommand(Command):
package = parts[1] package = parts[1]
version = parts[2] version = parts[2]
if not cache.has("{}:{}".format(package, version)): if not cache.has(f"{package}:{version}"):
self.line("No cache entries for {}:{}".format(package, version)) self.line(f"No cache entries for {package}:{version}")
return 0 return 0
delete = self.confirm("Delete cache entry {}:{}".format(package, version)) delete = self.confirm(f"Delete cache entry {package}:{version}")
if not delete: if not delete:
return 0 return 0
cache.forget("{}:{}".format(package, version)) cache.forget(f"{package}:{version}")
else: else:
raise ValueError("Invalid cache key") raise ValueError("Invalid cache key")
...@@ -17,7 +17,7 @@ class CacheListCommand(Command): ...@@ -17,7 +17,7 @@ class CacheListCommand(Command):
caches = sorted(REPOSITORY_CACHE_DIR.iterdir()) caches = sorted(REPOSITORY_CACHE_DIR.iterdir())
if caches: if caches:
for cache in caches: for cache in caches:
self.line("<info>{}</>".format(cache.name)) self.line(f"<info>{cache.name}</>")
return 0 return 0
self.line("<warning>No caches found</>") self.line("<warning>No caches found</>")
......
...@@ -22,9 +22,9 @@ class CheckCommand(Command): ...@@ -22,9 +22,9 @@ class CheckCommand(Command):
return 0 return 0
for error in check_result["errors"]: for error in check_result["errors"]:
self.line("<error>Error: {}</error>".format(error)) self.line(f"<error>Error: {error}</error>")
for error in check_result["warnings"]: for error in check_result["warnings"]:
self.line("<warning>Warning: {}</warning>".format(error)) self.line(f"<warning>Warning: {error}</warning>")
return 1 return 1
...@@ -138,11 +138,9 @@ To remove a repository (repo is a short alias for repositories): ...@@ -138,11 +138,9 @@ To remove a repository (repo is a short alias for repositories):
if config.get("repositories") is not None: if config.get("repositories") is not None:
value = config.get("repositories") value = config.get("repositories")
else: else:
repo = config.get("repositories.{}".format(m.group(1))) repo = config.get(f"repositories.{m.group(1)}")
if repo is None: if repo is None:
raise ValueError( raise ValueError(f"There is no {m.group(1)} repository defined")
"There is no {} repository defined".format(m.group(1))
)
value = repo value = repo
...@@ -150,7 +148,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -150,7 +148,7 @@ To remove a repository (repo is a short alias for repositories):
else: else:
values = self.unique_config_values values = self.unique_config_values
if setting_key not in values: if setting_key not in values:
raise ValueError("There is no {} setting.".format(setting_key)) raise ValueError(f"There is no {setting_key} setting.")
value = config.get(setting_key) value = config.get(setting_key)
...@@ -183,24 +181,18 @@ To remove a repository (repo is a short alias for repositories): ...@@ -183,24 +181,18 @@ To remove a repository (repo is a short alias for repositories):
raise ValueError("You cannot remove the [repositories] section") raise ValueError("You cannot remove the [repositories] section")
if self.option("unset"): if self.option("unset"):
repo = config.get("repositories.{}".format(m.group(1))) repo = config.get(f"repositories.{m.group(1)}")
if repo is None: if repo is None:
raise ValueError( raise ValueError(f"There is no {m.group(1)} repository defined")
"There is no {} repository defined".format(m.group(1))
)
config.config_source.remove_property( config.config_source.remove_property(f"repositories.{m.group(1)}")
"repositories.{}".format(m.group(1))
)
return 0 return 0
if len(values) == 1: if len(values) == 1:
url = values[0] url = values[0]
config.config_source.add_property( config.config_source.add_property(f"repositories.{m.group(1)}.url", url)
"repositories.{}.url".format(m.group(1)), url
)
return 0 return 0
...@@ -241,7 +233,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -241,7 +233,7 @@ To remove a repository (repo is a short alias for repositories):
elif m.group(1) == "pypi-token": elif m.group(1) == "pypi-token":
if len(values) != 1: if len(values) != 1:
raise ValueError( raise ValueError(
"Expected only one argument (token), got {}".format(len(values)) f"Expected only one argument (token), got {len(values)}"
) )
token = values[0] token = values[0]
...@@ -257,14 +249,14 @@ To remove a repository (repo is a short alias for repositories): ...@@ -257,14 +249,14 @@ To remove a repository (repo is a short alias for repositories):
if m: if m:
if self.option("unset"): if self.option("unset"):
config.auth_config_source.remove_property( config.auth_config_source.remove_property(
"certificates.{}.{}".format(m.group(1), m.group(2)) f"certificates.{m.group(1)}.{m.group(2)}"
) )
return 0 return 0
if len(values) == 1: if len(values) == 1:
config.auth_config_source.add_property( config.auth_config_source.add_property(
"certificates.{}.{}".format(m.group(1), m.group(2)), values[0] f"certificates.{m.group(1)}.{m.group(2)}", values[0]
) )
else: else:
raise ValueError("You must pass exactly 1 value") raise ValueError("You must pass exactly 1 value")
...@@ -287,7 +279,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -287,7 +279,7 @@ To remove a repository (repo is a short alias for repositories):
value = values[0] value = values[0]
if not validator(value): if not validator(value):
raise RuntimeError('"{}" is an invalid value for {}'.format(value, key)) raise RuntimeError(f'"{value}" is an invalid value for {key}')
source.add_property(key, normalizer(value)) source.add_property(key, normalizer(value))
...@@ -302,7 +294,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -302,7 +294,7 @@ To remove a repository (repo is a short alias for repositories):
raw_val = raw.get(key) raw_val = raw.get(key)
if isinstance(value, dict): if isinstance(value, dict):
k += "{}.".format(key) k += f"{key}."
self._list_configuration(value, raw_val, k=k) self._list_configuration(value, raw_val, k=k)
k = orig_k k = orig_k
...@@ -323,7 +315,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -323,7 +315,7 @@ To remove a repository (repo is a short alias for repositories):
k + key, json.dumps(raw_val), value k + key, json.dumps(raw_val), value
) )
else: else:
message = "<c1>{}</c1> = <c2>{}</c2>".format(k + key, json.dumps(value)) message = f"<c1>{k + key}</c1> = <c2>{json.dumps(value)}</c2>"
self.line(message) self.line(message)
......
...@@ -16,7 +16,7 @@ class DebugInfoCommand(Command): ...@@ -16,7 +16,7 @@ class DebugInfoCommand(Command):
self.line( self.line(
"\n".join( "\n".join(
[ [
"<info>Version</info>: <comment>{}</>".format(self.poetry.VERSION), f"<info>Version</info>: <comment>{self.poetry.VERSION}</>",
"<info>Python</info>: <comment>{}</>".format( "<info>Python</info>: <comment>{}</>".format(
poetry_python_version poetry_python_version
), ),
......
...@@ -131,8 +131,8 @@ class DebugResolveCommand(InitCommand): ...@@ -131,8 +131,8 @@ class DebugResolveCommand(InitCommand):
pkg = op.package pkg = op.package
row = [ row = [
"<c1>{}</c1>".format(pkg.complete_name), f"<c1>{pkg.complete_name}</c1>",
"<b>{}</b>".format(pkg.version), f"<b>{pkg.version}</b>",
] ]
if not pkg.marker.is_any(): if not pkg.marker.is_any():
......
...@@ -38,7 +38,7 @@ class EnvInfoCommand(Command): ...@@ -38,7 +38,7 @@ class EnvInfoCommand(Command):
self.line("") self.line("")
self.line("<b>Virtualenv</b>") self.line("<b>Virtualenv</b>")
listing = [ listing = [
"<info>Python</info>: <comment>{}</>".format(env_python_version), f"<info>Python</info>: <comment>{env_python_version}</>",
"<info>Implementation</info>: <comment>{}</>".format( "<info>Implementation</info>: <comment>{}</>".format(
env.python_implementation env.python_implementation
), ),
...@@ -64,13 +64,13 @@ class EnvInfoCommand(Command): ...@@ -64,13 +64,13 @@ class EnvInfoCommand(Command):
self.line( self.line(
"\n".join( "\n".join(
[ [
"<info>Platform</info>: <comment>{}</>".format(env.platform), f"<info>Platform</info>: <comment>{env.platform}</>",
"<info>OS</info>: <comment>{}</>".format(env.os), f"<info>OS</info>: <comment>{env.os}</>",
"<info>Python</info>: <comment>{}</>".format( "<info>Python</info>: <comment>{}</>".format(
".".join(str(v) for v in system_env.version_info[:3]) ".".join(str(v) for v in system_env.version_info[:3])
), ),
"<info>Path</info>: <comment>{}</>".format(system_env.path), f"<info>Path</info>: <comment>{system_env.path}</>",
"<info>Executable</info>: <comment>{}</>".format(system_env.python), f"<info>Executable</info>: <comment>{system_env.python}</>",
] ]
) )
) )
...@@ -22,7 +22,7 @@ class EnvListCommand(Command): ...@@ -22,7 +22,7 @@ class EnvListCommand(Command):
name = str(venv.path) name = str(venv.path)
if venv == current_env: if venv == current_env:
self.line("<info>{} (Activated)</info>".format(name)) self.line(f"<info>{name} (Activated)</info>")
continue continue
......
...@@ -38,8 +38,8 @@ class EnvRemoveCommand(Command): ...@@ -38,8 +38,8 @@ class EnvRemoveCommand(Command):
# TODO: refactor env.py to allow removal with one loop # TODO: refactor env.py to allow removal with one loop
for python in pythons: for python in pythons:
venv = manager.remove(python) venv = manager.remove(python)
self.line("Deleted virtualenv: <comment>{}</comment>".format(venv.path)) self.line(f"Deleted virtualenv: <comment>{venv.path}</comment>")
if all: if all:
for venv in manager.list(): for venv in manager.list():
manager.remove_venv(venv.path) manager.remove_venv(venv.path)
self.line("Deleted virtualenv: <comment>{}</comment>".format(venv.path)) self.line(f"Deleted virtualenv: <comment>{venv.path}</comment>")
...@@ -22,4 +22,4 @@ class EnvUseCommand(Command): ...@@ -22,4 +22,4 @@ class EnvUseCommand(Command):
env = manager.activate(self.argument("python"), self._io) env = manager.activate(self.argument("python"), self._io)
self.line("Using virtualenv: <comment>{}</>".format(env.path)) self.line(f"Using virtualenv: <comment>{env.path}</>")
...@@ -8,7 +8,7 @@ class EnvCommand(Command): ...@@ -8,7 +8,7 @@ class EnvCommand(Command):
def __init__(self) -> None: def __init__(self) -> None:
self._env = None self._env = None
super(EnvCommand, self).__init__() super().__init__()
@property @property
def env(self) -> Optional[Env]: def env(self) -> Optional[Env]:
......
...@@ -39,7 +39,7 @@ class ExportCommand(Command): ...@@ -39,7 +39,7 @@ class ExportCommand(Command):
fmt = self.option("format") fmt = self.option("format")
if fmt not in Exporter.ACCEPTED_FORMATS: if fmt not in Exporter.ACCEPTED_FORMATS:
raise ValueError("Invalid export format: {}".format(fmt)) raise ValueError(f"Invalid export format: {fmt}")
output = self.option("output") output = self.option("output")
......
...@@ -58,7 +58,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -58,7 +58,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
""" """
def __init__(self) -> None: def __init__(self) -> None:
super(InitCommand, self).__init__() super().__init__()
self._pool = None self._pool = None
...@@ -99,19 +99,19 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -99,19 +99,19 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
name = Path.cwd().name.lower() name = Path.cwd().name.lower()
question = self.create_question( question = self.create_question(
"Package name [<comment>{}</comment>]: ".format(name), default=name f"Package name [<comment>{name}</comment>]: ", default=name
) )
name = self.ask(question) name = self.ask(question)
version = "0.1.0" version = "0.1.0"
question = self.create_question( question = self.create_question(
"Version [<comment>{}</comment>]: ".format(version), default=version f"Version [<comment>{version}</comment>]: ", default=version
) )
version = self.ask(question) version = self.ask(question)
description = self.option("description") or "" description = self.option("description") or ""
question = self.create_question( question = self.create_question(
"Description [<comment>{}</comment>]: ".format(description), f"Description [<comment>{description}</comment>]: ",
default=description, default=description,
) )
description = self.ask(question) description = self.ask(question)
...@@ -121,10 +121,10 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -121,10 +121,10 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
author = vcs_config["user.name"] author = vcs_config["user.name"]
author_email = vcs_config.get("user.email") author_email = vcs_config.get("user.email")
if author_email: if author_email:
author += " <{}>".format(author_email) author += f" <{author_email}>"
question = self.create_question( question = self.create_question(
"Author [<comment>{}</comment>, n to skip]: ".format(author), default=author f"Author [<comment>{author}</comment>, n to skip]: ", default=author
) )
question.set_validator(lambda v: self._validate_author(v, author)) question.set_validator(lambda v: self._validate_author(v, author))
author = self.ask(question) author = self.ask(question)
...@@ -137,7 +137,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -137,7 +137,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
license = self.option("license") or "" license = self.option("license") or ""
question = self.create_question( question = self.create_question(
"License [<comment>{}</comment>]: ".format(license), default=license f"License [<comment>{license}</comment>]: ", default=license
) )
question.set_validator(self._validate_license) question.set_validator(self._validate_license)
license = self.ask(question) license = self.ask(question)
...@@ -252,7 +252,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -252,7 +252,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
or "path" in constraint or "path" in constraint
or "version" in constraint or "version" in constraint
): ):
self.line("Adding <info>{}</info>".format(package)) self.line(f"Adding <info>{package}</info>")
requires.append(constraint) requires.append(constraint)
package = self.ask("\nAdd a package:") package = self.ask("\nAdd a package:")
continue continue
...@@ -344,9 +344,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -344,9 +344,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
requirement["version"] = version requirement["version"] = version
requirement["name"] = name requirement["name"] = name
self.line( self.line(f"Using version <b>{version}</b> for <c1>{name}</c1>")
"Using version <b>{}</b> for <c1>{}</c1>".format(version, name)
)
else: else:
# check that the specified version/constraint exists # check that the specified version/constraint exists
# before we proceed # before we proceed
...@@ -379,9 +377,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -379,9 +377,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
if not package: if not package:
# TODO: find similar # TODO: find similar
raise ValueError( raise ValueError(f"Could not find a matching version of package {name}")
"Could not find a matching version of package {}".format(name)
)
return package.pretty_name, selector.find_recommended_require_version(package) return package.pretty_name, selector.find_recommended_require_version(package)
......
...@@ -12,10 +12,10 @@ class InstallerCommand(EnvCommand): ...@@ -12,10 +12,10 @@ class InstallerCommand(EnvCommand):
def __init__(self) -> None: def __init__(self) -> None:
self._installer: Optional["Installer"] = None self._installer: Optional["Installer"] = None
super(InstallerCommand, self).__init__() super().__init__()
def reset_poetry(self) -> None: def reset_poetry(self) -> None:
super(InstallerCommand, self).reset_poetry() super().reset_poetry()
self._installer.set_package(self.poetry.package) self._installer.set_package(self.poetry.package)
self._installer.set_locker(self.poetry.locker) self._installer.set_locker(self.poetry.locker)
......
...@@ -60,7 +60,7 @@ class NewCommand(Command): ...@@ -60,7 +60,7 @@ class NewCommand(Command):
author = config["user.name"] author = config["user.name"]
author_email = config.get("user.email") author_email = config.get("user.email")
if author_email: if author_email:
author += " <{}>".format(author_email) author += f" <{author_email}>"
current_env = SystemEnv(Path(sys.executable)) current_env = SystemEnv(Path(sys.executable))
default_python = "^{}".format( default_python = "^{}".format(
......
...@@ -193,7 +193,7 @@ You can specify a package in the following forms: ...@@ -193,7 +193,7 @@ You can specify a package in the following forms:
"<c2>pyproject.toml</c2> file and will be skipped:\n" "<c2>pyproject.toml</c2> file and will be skipped:\n"
) )
for name in existing_packages: for name in existing_packages:
self.line(" • <c1>{name}</c1>".format(name=name)) self.line(f" • <c1>{name}</c1>")
self.line( self.line(
"\nIf you want to update it to the latest compatible version, " "\nIf you want to update it to the latest compatible version, "
......
...@@ -17,11 +17,11 @@ class SearchCommand(Command): ...@@ -17,11 +17,11 @@ class SearchCommand(Command):
for result in results: for result in results:
self.line("") self.line("")
name = "<info>{}</>".format(result.name) name = f"<info>{result.name}</>"
name += " (<comment>{}</>)".format(result.version) name += f" (<comment>{result.version}</>)"
self.line(name) self.line(name)
if result.description: if result.description:
self.line(" {}".format(result.description)) self.line(f" {result.description}")
...@@ -130,7 +130,7 @@ class SelfUpdateCommand(Command): ...@@ -130,7 +130,7 @@ class SelfUpdateCommand(Command):
self.line("You are using the latest version") self.line("You are using the latest version")
return 0 return 0
self.line("Updating <c1>Poetry</c1> to <c2>{}</c2>".format(release.version)) self.line(f"Updating <c1>Poetry</c1> to <c2>{release.version}</c2>")
self.line("") self.line("")
self.update(release) self.update(release)
......
...@@ -31,7 +31,7 @@ If one doesn't exist yet, it will be created. ...@@ -31,7 +31,7 @@ If one doesn't exist yet, it will be created.
return return
self.line("Spawning shell within <info>{}</>".format(self.env.path)) self.line(f"Spawning shell within <info>{self.env.path}</>")
# Setting this to avoid spawning unnecessary nested shells # Setting this to avoid spawning unnecessary nested shells
environ["POETRY_ACTIVE"] = "1" environ["POETRY_ACTIVE"] = "1"
......
...@@ -173,7 +173,7 @@ lists all packages available.""" ...@@ -173,7 +173,7 @@ lists all packages available."""
break break
if not pkg: if not pkg:
raise ValueError("Package {} not found".format(package)) raise ValueError(f"Package {package} not found")
if self.option("tree"): if self.option("tree"):
self.display_package_tree(self.io, pkg, locked_repo) self.display_package_tree(self.io, pkg, locked_repo)
...@@ -188,9 +188,9 @@ lists all packages available.""" ...@@ -188,9 +188,9 @@ lists all packages available."""
required_by[locked.pretty_name] = dependencies[pkg.name] required_by[locked.pretty_name] = dependencies[pkg.name]
rows = [ rows = [
["<info>name</>", " : <c1>{}</>".format(pkg.pretty_name)], ["<info>name</>", f" : <c1>{pkg.pretty_name}</>"],
["<info>version</>", " : <b>{}</b>".format(pkg.pretty_version)], ["<info>version</>", f" : <b>{pkg.pretty_version}</b>"],
["<info>description</>", " : {}".format(pkg.description)], ["<info>description</>", f" : {pkg.description}"],
] ]
table.add_rows(rows) table.add_rows(rows)
...@@ -210,9 +210,7 @@ lists all packages available.""" ...@@ -210,9 +210,7 @@ lists all packages available."""
self.line("") self.line("")
self.line("<info>required by</info>") self.line("<info>required by</info>")
for parent, requires_version in required_by.items(): for parent, requires_version in required_by.items():
self.line( self.line(f" - <c1>{parent}</c1> <b>{requires_version}</b>")
" - <c1>{}</c1> <b>{}</b>".format(parent, requires_version)
)
return 0 return 0
...@@ -351,12 +349,12 @@ lists all packages available.""" ...@@ -351,12 +349,12 @@ lists all packages available."""
def display_package_tree( def display_package_tree(
self, io: "IO", package: "Package", installed_repo: "Repository" self, io: "IO", package: "Package", installed_repo: "Repository"
) -> None: ) -> None:
io.write("<c1>{}</c1>".format(package.pretty_name)) io.write(f"<c1>{package.pretty_name}</c1>")
description = "" description = ""
if package.description: if package.description:
description = " " + package.description description = " " + package.description
io.write_line(" <b>{}</b>{}".format(package.pretty_version, description)) io.write_line(f" <b>{package.pretty_version}</b>{description}")
dependencies = package.requires dependencies = package.requires
dependencies = sorted(dependencies, key=lambda x: x.name) dependencies = sorted(dependencies, key=lambda x: x.name)
...@@ -481,7 +479,7 @@ lists all packages available.""" ...@@ -481,7 +479,7 @@ lists all packages available."""
name = package.name name = package.name
selector = VersionSelector(self.poetry.pool) selector = VersionSelector(self.poetry.pool)
return selector.find_best_candidate(name, ">={}".format(package.pretty_version)) return selector.find_best_candidate(name, f">={package.pretty_version}")
def get_update_status(self, latest: "Package", package: "Package") -> str: def get_update_status(self, latest: "Package", package: "Package") -> str:
from poetry.core.semver.helpers import parse_constraint from poetry.core.semver.helpers import parse_constraint
......
...@@ -41,15 +41,15 @@ class SourceShowCommand(Command): ...@@ -41,15 +41,15 @@ class SourceShowCommand(Command):
table = self.table(style="compact") table = self.table(style="compact")
rows = [ rows = [
["<info>name</>", " : <c1>{}</>".format(source.name)], ["<info>name</>", f" : <c1>{source.name}</>"],
["<info>url</>", " : {}".format(source.url)], ["<info>url</>", f" : {source.url}"],
[ [
"<info>default</>", "<info>default</>",
" : {}".format(bool_string.get(source.default, False)), f" : {bool_string.get(source.default, False)}",
], ],
[ [
"<info>secondary</>", "<info>secondary</>",
" : {}".format(bool_string.get(source.secondary, False)), f" : {bool_string.get(source.secondary, False)}",
], ],
] ]
table.add_rows(rows) table.add_rows(rows)
......
...@@ -55,7 +55,7 @@ patch, minor, major, prepatch, preminor, premajor, prerelease. ...@@ -55,7 +55,7 @@ patch, minor, major, prepatch, preminor, premajor, prerelease.
) )
if self.option("short"): if self.option("short"):
self.line("{}".format(version)) self.line(f"{version}")
else: else:
self.line( self.line(
"Bumping version from <b>{}</> to <fg=green>{}</>".format( "Bumping version from <b>{}</> to <fg=green>{}</>".format(
...@@ -70,7 +70,7 @@ patch, minor, major, prepatch, preminor, premajor, prerelease. ...@@ -70,7 +70,7 @@ patch, minor, major, prepatch, preminor, premajor, prerelease.
self.poetry.file.write(content) self.poetry.file.write(content)
else: else:
if self.option("short"): if self.option("short"):
self.line("{}".format(self.poetry.package.pretty_version)) self.line(f"{self.poetry.package.pretty_version}")
else: else:
self.line( self.line(
"<comment>{}</> <info>{}</>".format( "<comment>{}</> <info>{}</>".format(
......
import logging import logging
class Formatter(object): class Formatter:
def format(self, record: logging.LogRecord) -> str: def format(self, record: logging.LogRecord) -> str:
raise NotImplementedError() raise NotImplementedError()
...@@ -26,8 +26,8 @@ class IOFormatter(logging.Formatter): ...@@ -26,8 +26,8 @@ class IOFormatter(logging.Formatter):
if record.name in FORMATTERS: if record.name in FORMATTERS:
msg = FORMATTERS[record.name].format(msg) msg = FORMATTERS[record.name].format(msg)
elif level in self._colors: elif level in self._colors:
msg = "<{}>{}</>".format(self._colors[level], msg) msg = f"<{self._colors[level]}>{msg}</>"
return msg return msg
return super(IOFormatter, self).format(record) return super().format(record)
...@@ -13,7 +13,7 @@ class IOHandler(logging.Handler): ...@@ -13,7 +13,7 @@ class IOHandler(logging.Handler):
def __init__(self, io: "IO") -> None: def __init__(self, io: "IO") -> None:
self._io = io self._io = io
super(IOHandler, self).__init__() super().__init__()
def emit(self, record: "LogRecord") -> None: def emit(self, record: "LogRecord") -> None:
try: try:
......
...@@ -36,7 +36,7 @@ class Factory(BaseFactory): ...@@ -36,7 +36,7 @@ class Factory(BaseFactory):
if io is None: if io is None:
io = NullIO() io = NullIO()
base_poetry = super(Factory, self).create_poetry(cwd) base_poetry = super().create_poetry(cwd)
locker = Locker( locker = Locker(
base_poetry.file.parent / "poetry.lock", base_poetry.local_config base_poetry.file.parent / "poetry.lock", base_poetry.local_config
...@@ -49,9 +49,7 @@ class Factory(BaseFactory): ...@@ -49,9 +49,7 @@ class Factory(BaseFactory):
local_config_file = TOMLFile(base_poetry.file.parent / "poetry.toml") local_config_file = TOMLFile(base_poetry.file.parent / "poetry.toml")
if local_config_file.exists(): if local_config_file.exists():
if io.is_debug(): if io.is_debug():
io.write_line( io.write_line(f"Loading configuration file {local_config_file.path}")
"Loading configuration file {}".format(local_config_file.path)
)
config.merge(local_config_file.read()) config.merge(local_config_file.read())
......
...@@ -44,9 +44,7 @@ class PackageInfoError(ValueError): ...@@ -44,9 +44,7 @@ class PackageInfoError(ValueError):
def __init__( def __init__(
self, path: Union[Path, str], *reasons: Union[BaseException, str] self, path: Union[Path, str], *reasons: Union[BaseException, str]
) -> None: ) -> None:
reasons = ( reasons = (f"Unable to determine package info for path: {str(path)}",) + reasons
"Unable to determine package info for path: {}".format(str(path)),
) + reasons
super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg)) super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg))
......
...@@ -12,7 +12,7 @@ class Install(Operation): ...@@ -12,7 +12,7 @@ class Install(Operation):
def __init__( def __init__(
self, package: "Package", reason: Optional[str] = None, priority: int = 0 self, package: "Package", reason: Optional[str] = None, priority: int = 0
) -> None: ) -> None:
super(Install, self).__init__(reason, priority=priority) super().__init__(reason, priority=priority)
self._package = package self._package = package
......
...@@ -6,7 +6,7 @@ if TYPE_CHECKING: ...@@ -6,7 +6,7 @@ if TYPE_CHECKING:
from poetry.core.packages.package import Package from poetry.core.packages.package import Package
class Operation(object): class Operation:
def __init__(self, reason: Optional[str] = None, priority: int = 0) -> None: def __init__(self, reason: Optional[str] = None, priority: int = 0) -> None:
self._reason = reason self._reason = reason
......
...@@ -15,7 +15,7 @@ class Uninstall(Operation): ...@@ -15,7 +15,7 @@ class Uninstall(Operation):
reason: Optional[str] = None, reason: Optional[str] = None,
priority: int = float("inf"), priority: int = float("inf"),
) -> None: ) -> None:
super(Uninstall, self).__init__(reason, priority=priority) super().__init__(reason, priority=priority)
self._package = package self._package = package
......
...@@ -19,7 +19,7 @@ class Update(Operation): ...@@ -19,7 +19,7 @@ class Update(Operation):
self._initial_package = initial self._initial_package = initial
self._target_package = target self._target_package = target
super(Update, self).__init__(reason, priority=priority) super().__init__(reason, priority=priority)
@property @property
def initial_package(self) -> "Package": def initial_package(self) -> "Package":
......
...@@ -131,7 +131,7 @@ class Layout: ...@@ -131,7 +131,7 @@ class Layout:
else: else:
poetry_content.remove("license") poetry_content.remove("license")
poetry_content["readme"] = "README.{}".format(self._readme_format) poetry_content["readme"] = f"README.{self._readme_format}"
packages = self.get_package_include() packages = self.get_package_include()
if packages: if packages:
poetry_content["packages"].append(packages) poetry_content["packages"].append(packages)
...@@ -182,7 +182,7 @@ class Layout: ...@@ -182,7 +182,7 @@ class Layout:
package_init.touch() package_init.touch()
def _create_readme(self, path: "Path") -> "Path": def _create_readme(self, path: "Path") -> "Path":
readme_file = path.joinpath("README.{}".format(self._readme_format)) readme_file = path.joinpath(f"README.{self._readme_format}")
readme_file.touch() readme_file.touch()
return readme_file return readme_file
......
...@@ -39,7 +39,7 @@ WINDOWS_CMD_TEMPLATE = """\ ...@@ -39,7 +39,7 @@ WINDOWS_CMD_TEMPLATE = """\
class EditableBuilder(Builder): class EditableBuilder(Builder):
def __init__(self, poetry: "Poetry", env: "Env", io: "IO") -> None: def __init__(self, poetry: "Poetry", env: "Env", io: "IO") -> None:
super(EditableBuilder, self).__init__(poetry) super().__init__(poetry)
self._env = env self._env = env
self._io = io self._io = io
...@@ -75,7 +75,7 @@ class EditableBuilder(Builder): ...@@ -75,7 +75,7 @@ class EditableBuilder(Builder):
self._add_dist_info(added_files) self._add_dist_info(added_files)
def _run_build_script(self, build_script: Path) -> None: def _run_build_script(self, build_script: Path) -> None:
self._debug(" - Executing build script: <b>{}</b>".format(build_script)) self._debug(f" - Executing build script: <b>{build_script}</b>")
self._env.run("python", str(self._path.joinpath(build_script)), call=True) self._env.run("python", str(self._path.joinpath(build_script)), call=True)
def _setup_build(self) -> None: def _setup_build(self) -> None:
...@@ -249,7 +249,7 @@ class EditableBuilder(Builder): ...@@ -249,7 +249,7 @@ class EditableBuilder(Builder):
for path in added_files: for path in added_files:
hash = self._get_file_hash(path) hash = self._get_file_hash(path)
size = path.stat().st_size size = path.stat().st_size
f.write("{},sha256={},{}\n".format(str(path), hash, size)) f.write(f"{str(path)},sha256={hash},{size}\n")
# RECORD itself is recorded with no hash or size # RECORD itself is recorded with no hash or size
f.write("{},,\n".format(dist_info.joinpath("RECORD"))) f.write("{},,\n".format(dist_info.joinpath("RECORD")))
......
...@@ -69,7 +69,7 @@ class _Writer: ...@@ -69,7 +69,7 @@ class _Writer:
padding = ( padding = (
0 0
if not self._line_numbers if not self._line_numbers
else len("({}) ".format(list(self._line_numbers.values())[-1])) else len(f"({list(self._line_numbers.values())[-1]}) ")
) )
last_was_empty = False last_was_empty = False
......
...@@ -134,7 +134,7 @@ class Incompatibility: ...@@ -134,7 +134,7 @@ class Incompatibility:
assert self._terms[0].is_positive() assert self._terms[0].is_positive()
cause: PythonCause = self._cause cause: PythonCause = self._cause
text = "{} requires ".format(self._terse(self._terms[0], allow_every=True)) text = f"{self._terse(self._terms[0], allow_every=True)} requires "
text += f"Python {cause.python_version}" text += f"Python {cause.python_version}"
return text return text
...@@ -143,7 +143,7 @@ class Incompatibility: ...@@ -143,7 +143,7 @@ class Incompatibility:
assert self._terms[0].is_positive() assert self._terms[0].is_positive()
cause: PlatformCause = self._cause cause: PlatformCause = self._cause
text = "{} requires ".format(self._terse(self._terms[0], allow_every=True)) text = f"{self._terse(self._terms[0], allow_every=True)} requires "
text += f"platform {cause.platform}" text += f"platform {cause.platform}"
return text return text
...@@ -158,7 +158,7 @@ class Incompatibility: ...@@ -158,7 +158,7 @@ class Incompatibility:
assert len(self._terms) == 1 assert len(self._terms) == 1
assert self._terms[0].is_positive() assert self._terms[0].is_positive()
return "{} doesn't exist".format(self._terms[0].dependency.name) return f"{self._terms[0].dependency.name} doesn't exist"
elif isinstance(self._cause, RootCause): elif isinstance(self._cause, RootCause):
assert len(self._terms) == 1 assert len(self._terms) == 1
assert not self._terms[0].is_positive() assert not self._terms[0].is_positive()
...@@ -258,7 +258,7 @@ class Incompatibility: ...@@ -258,7 +258,7 @@ class Incompatibility:
if this_line is not None: if this_line is not None:
buffer.append(" " + str(this_line)) buffer.append(" " + str(this_line))
buffer.append(" and {}".format(str(other))) buffer.append(f" and {str(other)}")
if other_line is not None: if other_line is not None:
buffer.append(" " + str(other_line)) buffer.append(" " + str(other_line))
...@@ -368,7 +368,7 @@ class Incompatibility: ...@@ -368,7 +368,7 @@ class Incompatibility:
verb = "requires" verb = "requires"
buffer.append( buffer.append(
"{} {} ".format(self._terse(prior_positives[0], allow_every=True), verb) f"{self._terse(prior_positives[0], allow_every=True)} {verb} "
) )
buffer.append(self._terse(prior_negative)) buffer.append(self._terse(prior_negative))
...@@ -474,4 +474,4 @@ class Incompatibility: ...@@ -474,4 +474,4 @@ class Incompatibility:
return found return found
def __repr__(self) -> str: def __repr__(self) -> str:
return "<Incompatibility {}>".format(str(self)) return f"<Incompatibility {str(self)}>"
...@@ -165,4 +165,4 @@ class Term: ...@@ -165,4 +165,4 @@ class Term:
return "{}{}".format("not " if not self.is_positive() else "", self._dependency) return "{}{}".format("not " if not self.is_positive() else "", self._dependency)
def __repr__(self) -> str: def __repr__(self) -> str:
return "<Term {}>".format(str(self)) return f"<Term {str(self)}>"
...@@ -477,7 +477,7 @@ class Locker: ...@@ -477,7 +477,7 @@ class Locker:
# We expect the locker to be able to read lock files # We expect the locker to be able to read lock files
# from the same semantic versioning range # from the same semantic versioning range
accepted_versions = parse_constraint( accepted_versions = parse_constraint(
"^{}".format(Version.from_parts(current_version.major, 0)) f"^{Version.from_parts(current_version.major, 0)}"
) )
lock_version_allowed = accepted_versions.allows(lock_version) lock_version_allowed = accepted_versions.allows(lock_version)
if lock_version_allowed and current_version < lock_version: if lock_version_allowed and current_version < lock_version:
......
...@@ -30,7 +30,7 @@ class Poetry(BasePoetry): ...@@ -30,7 +30,7 @@ class Poetry(BasePoetry):
): ):
from poetry.repositories.pool import Pool from poetry.repositories.pool import Pool
super(Poetry, self).__init__(file, local_config, package) super().__init__(file, local_config, package)
self._locker = locker self._locker = locker
self._config = config self._config = config
......
...@@ -587,9 +587,7 @@ class Provider: ...@@ -587,9 +587,7 @@ class Provider:
continue continue
if len(by_constraint) == 1: if len(by_constraint) == 1:
self.debug( self.debug(f"<debug>Merging requirements for {str(deps[0])}</debug>")
"<debug>Merging requirements for {}</debug>".format(str(deps[0]))
)
dependencies.append(list(by_constraint.values())[0][0]) dependencies.append(list(by_constraint.values())[0][0])
continue continue
...@@ -728,7 +726,7 @@ class Provider: ...@@ -728,7 +726,7 @@ class Provider:
m2 = re.match(r"(.+?) \((.+?)\)", m.group(1)) m2 = re.match(r"(.+?) \((.+?)\)", m.group(1))
if m2: if m2:
name = m2.group(1) name = m2.group(1)
version = " (<c2>{}</c2>)".format(m2.group(2)) version = f" (<c2>{m2.group(2)}</c2>)"
else: else:
name = m.group(1) name = m.group(1)
version = "" version = ""
...@@ -772,7 +770,7 @@ class Provider: ...@@ -772,7 +770,7 @@ class Provider:
m2 = re.match(r"(.+?) \((.+?)\)", m.group(1)) m2 = re.match(r"(.+?) \((.+?)\)", m.group(1))
if m2: if m2:
name = m2.group(1) name = m2.group(1)
version = " (<c2>{}</c2>)".format(m2.group(2)) version = f" (<c2>{m2.group(2)}</c2>)"
else: else:
name = m.group(1) name = m.group(1)
version = "" version = ""
...@@ -795,7 +793,7 @@ class Provider: ...@@ -795,7 +793,7 @@ class Provider:
debug_info = ( debug_info = (
"\n".join( "\n".join(
[ [
"<debug>{}:</debug> {}".format(str(depth).rjust(4), s) f"<debug>{str(depth).rjust(4)}:</debug> {s}"
for s in debug_info.split("\n") for s in debug_info.split("\n")
] ]
) )
......
...@@ -248,7 +248,7 @@ class LegacyRepository(PyPiRepository): ...@@ -248,7 +248,7 @@ class LegacyRepository(PyPiRepository):
key = dependency.name key = dependency.name
if not constraint.is_any(): if not constraint.is_any():
key = "{}:{}".format(key, str(constraint)) key = f"{key}:{str(constraint)}"
ignored_pre_release_versions = [] ignored_pre_release_versions = []
......
...@@ -110,7 +110,7 @@ class PyPiRepository(RemoteRepository): ...@@ -110,7 +110,7 @@ class PyPiRepository(RemoteRepository):
info = self.get_package_info(dependency.name) info = self.get_package_info(dependency.name)
except PackageNotFound: except PackageNotFound:
self._log( self._log(
"No packages found for {} {}".format(dependency.name, str(constraint)), f"No packages found for {dependency.name} {str(constraint)}",
level="debug", level="debug",
) )
return [] return []
......
...@@ -274,8 +274,8 @@ class SitePackages: ...@@ -274,8 +274,8 @@ class SitePackages:
str, self._candidates if not writable_only else self.writable_candidates str, self._candidates if not writable_only else self.writable_candidates
) )
) )
for distribution in metadata.PathDistribution.discover(name=name, path=path):
yield distribution yield from metadata.PathDistribution.discover(name=name, path=path)
def find_distribution( def find_distribution(
self, name: str, writable_only: bool = False self, name: str, writable_only: bool = False
...@@ -373,7 +373,7 @@ class SitePackages: ...@@ -373,7 +373,7 @@ class SitePackages:
if results: if results:
return results return results
raise OSError("Unable to access any of {}".format(paths_csv(candidates))) raise OSError(f"Unable to access any of {paths_csv(candidates)}")
def write_text(self, path: Union[str, Path], *args: Any, **kwargs: Any) -> Path: def write_text(self, path: Union[str, Path], *args: Any, **kwargs: Any) -> Path:
return self._path_method_wrapper(path, "write_text", *args, **kwargs)[0] return self._path_method_wrapper(path, "write_text", *args, **kwargs)[0]
...@@ -902,9 +902,7 @@ class EnvManager: ...@@ -902,9 +902,7 @@ class EnvManager:
return self.get_system_env() return self.get_system_env()
io.write_line( io.write_line(f"Creating virtualenv <c1>{name}</> in {str(venv_path)}")
"Creating virtualenv <c1>{}</> in {}".format(name, str(venv_path))
)
else: else:
create_venv = False create_venv = False
if force: if force:
...@@ -914,9 +912,7 @@ class EnvManager: ...@@ -914,9 +912,7 @@ class EnvManager:
env.path env.path
) )
) )
io.write_line( io.write_line(f"Recreating virtualenv <c1>{name}</> in {str(venv)}")
"Recreating virtualenv <c1>{}</> in {}".format(name, str(venv))
)
self.remove_venv(venv) self.remove_venv(venv)
create_venv = True create_venv = True
elif io.is_very_verbose(): elif io.is_very_verbose():
...@@ -1144,11 +1140,9 @@ class Env: ...@@ -1144,11 +1140,9 @@ class Env:
def find_executables(self) -> None: def find_executables(self) -> None:
python_executables = sorted( python_executables = sorted(
[
p.name p.name
for p in self._bin_dir.glob("python*") for p in self._bin_dir.glob("python*")
if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name) if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
) )
if python_executables: if python_executables:
executable = python_executables[0] executable = python_executables[0]
...@@ -1158,11 +1152,9 @@ class Env: ...@@ -1158,11 +1152,9 @@ class Env:
self._executable = executable self._executable = executable
pip_executables = sorted( pip_executables = sorted(
[
p.name p.name
for p in self._bin_dir.glob("pip*") for p in self._bin_dir.glob("pip*")
if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name) if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
) )
if pip_executables: if pip_executables:
pip_executable = pip_executables[0] pip_executable = pip_executables[0]
...@@ -1173,7 +1165,7 @@ class Env: ...@@ -1173,7 +1165,7 @@ class Env:
def get_embedded_wheel(self, distribution): def get_embedded_wheel(self, distribution):
return get_embed_wheel( return get_embed_wheel(
distribution, "{}.{}".format(self.version_info[0], self.version_info[1]) distribution, f"{self.version_info[0]}.{self.version_info[1]}"
).path ).path
@property @property
...@@ -1554,7 +1546,7 @@ class VirtualEnv(Env): ...@@ -1554,7 +1546,7 @@ class VirtualEnv(Env):
def get_version_info(self) -> Tuple[int]: def get_version_info(self) -> Tuple[int]:
output = self.run_python_script(GET_PYTHON_VERSION) output = self.run_python_script(GET_PYTHON_VERSION)
return tuple([int(s) for s in output.strip().split(".")]) return tuple(int(s) for s in output.strip().split("."))
def get_python_implementation(self) -> str: def get_python_implementation(self) -> str:
return self.marker_env["platform_python_implementation"] return self.marker_env["platform_python_implementation"]
...@@ -1680,10 +1672,10 @@ class GenericEnv(VirtualEnv): ...@@ -1680,10 +1672,10 @@ class GenericEnv(VirtualEnv):
minor_version = "{}.{}".format( minor_version = "{}.{}".format(
self._child_env.version_info[0], self._child_env.version_info[1] self._child_env.version_info[0], self._child_env.version_info[1]
) )
major_version = "{}".format(self._child_env.version_info[0]) major_version = f"{self._child_env.version_info[0]}"
patterns = [ patterns = [
("python{}".format(minor_version), "pip{}".format(minor_version)), (f"python{minor_version}", f"pip{minor_version}"),
("python{}".format(major_version), "pip{}".format(major_version)), (f"python{major_version}", f"pip{major_version}"),
] ]
python_executable = None python_executable = None
...@@ -1695,11 +1687,9 @@ class GenericEnv(VirtualEnv): ...@@ -1695,11 +1687,9 @@ class GenericEnv(VirtualEnv):
if not python_executable: if not python_executable:
python_executables = sorted( python_executables = sorted(
[
p.name p.name
for p in self._bin_dir.glob(python_pattern) for p in self._bin_dir.glob(python_pattern)
if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name) if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
) )
if python_executables: if python_executables:
...@@ -1711,11 +1701,9 @@ class GenericEnv(VirtualEnv): ...@@ -1711,11 +1701,9 @@ class GenericEnv(VirtualEnv):
if not pip_executable: if not pip_executable:
pip_executables = sorted( pip_executables = sorted(
[
p.name p.name
for p in self._bin_dir.glob(pip_pattern) for p in self._bin_dir.glob(pip_pattern)
if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name) if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
) )
if pip_executables: if pip_executables:
pip_executable = pip_executables[0] pip_executable = pip_executables[0]
......
...@@ -120,7 +120,7 @@ def get_package_version_display_string( ...@@ -120,7 +120,7 @@ def get_package_version_display_string(
def paths_csv(paths: List[Path]) -> str: def paths_csv(paths: List[Path]) -> str:
return ", ".join('"{}"'.format(str(c)) for c in paths) return ", ".join(f'"{str(c)}"' for c in paths)
def is_dir_writable(path: Path, create: bool = False) -> bool: def is_dir_writable(path: Path, create: bool = False) -> bool:
......
...@@ -88,7 +88,7 @@ class KeyRing: ...@@ -88,7 +88,7 @@ class KeyRing:
try: try:
import keyring import keyring
except Exception as e: except Exception as e:
logger.debug("An error occurred while importing keyring: {}".format(str(e))) logger.debug(f"An error occurred while importing keyring: {str(e)}")
self._is_available = False self._is_available = False
return return
......
...@@ -80,9 +80,7 @@ class Shell: ...@@ -80,9 +80,7 @@ class Shell:
activate_script = self._get_activate_script() activate_script = self._get_activate_script()
bin_dir = "Scripts" if WINDOWS else "bin" bin_dir = "Scripts" if WINDOWS else "bin"
activate_path = env.path / bin_dir / activate_script activate_path = env.path / bin_dir / activate_script
c.sendline( c.sendline(f"{self._get_source_command()} {shlex.quote(str(activate_path))}")
"{} {}".format(self._get_source_command(), shlex.quote(str(activate_path)))
)
def resize(sig: Any, data: Any) -> None: def resize(sig: Any, data: Any) -> None:
terminal = Terminal() terminal = Terminal()
......
...@@ -15,7 +15,7 @@ def get_boolean_options(config=None): ...@@ -15,7 +15,7 @@ def get_boolean_options(config=None):
yield k yield k
if isinstance(v, dict): if isinstance(v, dict):
for suboption in get_boolean_options(v): for suboption in get_boolean_options(v):
yield "{}.{}".format(k, suboption) yield f"{k}.{suboption}"
@pytest.mark.parametrize( @pytest.mark.parametrize(
......
...@@ -39,19 +39,19 @@ class Config(BaseConfig): ...@@ -39,19 +39,19 @@ class Config(BaseConfig):
self.merge(self._config_source.config) self.merge(self._config_source.config)
self.merge(self._auth_config_source.config) self.merge(self._auth_config_source.config)
return super(Config, self).get(setting_name, default=default) return super().get(setting_name, default=default)
def raw(self) -> Dict[str, Any]: def raw(self) -> Dict[str, Any]:
self.merge(self._config_source.config) self.merge(self._config_source.config)
self.merge(self._auth_config_source.config) self.merge(self._auth_config_source.config)
return super(Config, self).raw() return super().raw()
def all(self) -> Dict[str, Any]: def all(self) -> Dict[str, Any]:
self.merge(self._config_source.config) self.merge(self._config_source.config)
self.merge(self._auth_config_source.config) self.merge(self._auth_config_source.config)
return super(Config, self).all() return super().all()
class DummyBackend(KeyringBackend): class DummyBackend(KeyringBackend):
...@@ -308,7 +308,7 @@ def project_factory(tmp_dir, config, repo, installed, default_python): ...@@ -308,7 +308,7 @@ def project_factory(tmp_dir, config, repo, installed, default_python):
poetry_lock_content=None, poetry_lock_content=None,
install_deps=True, install_deps=True,
): ):
project_dir = workspace / "poetry-fixture-{}".format(name) project_dir = workspace / f"poetry-fixture-{name}"
dependencies = dependencies or {} dependencies = dependencies or {}
dev_dependencies = dev_dependencies or {} dev_dependencies = dev_dependencies or {}
......
...@@ -33,7 +33,7 @@ def venvs_in_cache_dirs( ...@@ -33,7 +33,7 @@ def venvs_in_cache_dirs(
): ):
directories = [] directories = []
for version in python_versions: for version in python_versions:
directory = venv_cache.joinpath("{}-py{}".format(venv_name, version)) directory = venv_cache.joinpath(f"{venv_name}-py{version}")
directory.mkdir(parents=True, exist_ok=True) directory.mkdir(parents=True, exist_ok=True)
directories.append(directory.name) directories.append(directory.name)
return directories return directories
......
...@@ -17,7 +17,7 @@ def check_output_wrapper(version=VERSION_3_7_1): ...@@ -17,7 +17,7 @@ def check_output_wrapper(version=VERSION_3_7_1):
if "sys.version_info[:3]" in cmd: if "sys.version_info[:3]" in cmd:
return version.text return version.text
elif "sys.version_info[:2]" in cmd: elif "sys.version_info[:2]" in cmd:
return "{}.{}".format(version.major, version.minor) return f"{version.major}.{version.minor}"
else: else:
return str(Path("/prefix")) return str(Path("/prefix"))
......
...@@ -20,11 +20,9 @@ def test_remove_by_python_version( ...@@ -20,11 +20,9 @@ def test_remove_by_python_version(
tester.execute("3.6") tester.execute("3.6")
assert check_output.called assert check_output.called
assert not (venv_cache / "{}-py3.6".format(venv_name)).exists() assert not (venv_cache / f"{venv_name}-py3.6").exists()
expected = "Deleted virtualenv: {}\n".format( expected = "Deleted virtualenv: {}\n".format(venv_cache / f"{venv_name}-py3.6")
(venv_cache / "{}-py3.6".format(venv_name))
)
assert expected == tester.io.fetch_output() assert expected == tester.io.fetch_output()
...@@ -36,7 +34,7 @@ def test_remove_by_name(tester, venvs_in_cache_dirs, venv_name, venv_cache): ...@@ -36,7 +34,7 @@ def test_remove_by_name(tester, venvs_in_cache_dirs, venv_name, venv_cache):
assert not (venv_cache / name).exists() assert not (venv_cache / name).exists()
expected += "Deleted virtualenv: {}\n".format((venv_cache / name)) expected += f"Deleted virtualenv: {venv_cache / name}\n"
assert expected == tester.io.fetch_output() assert expected == tester.io.fetch_output()
...@@ -46,16 +44,16 @@ def test_remove_all(tester, venvs_in_cache_dirs, venv_name, venv_cache): ...@@ -46,16 +44,16 @@ def test_remove_all(tester, venvs_in_cache_dirs, venv_name, venv_cache):
tester.execute("--all") tester.execute("--all")
for name in venvs_in_cache_dirs: for name in venvs_in_cache_dirs:
assert not (venv_cache / name).exists() assert not (venv_cache / name).exists()
expected.add("Deleted virtualenv: {}".format((venv_cache / name))) expected.add(f"Deleted virtualenv: {venv_cache / name}")
assert expected == set(tester.io.fetch_output().split("\n")) assert expected == set(tester.io.fetch_output().split("\n"))
def test_remove_all_and_version(tester, venvs_in_cache_dirs, venv_name, venv_cache): def test_remove_all_and_version(tester, venvs_in_cache_dirs, venv_name, venv_cache):
expected = {""} expected = {""}
tester.execute("--all {}".format(venvs_in_cache_dirs[0])) tester.execute(f"--all {venvs_in_cache_dirs[0]}")
for name in venvs_in_cache_dirs: for name in venvs_in_cache_dirs:
assert not (venv_cache / name).exists() assert not (venv_cache / name).exists()
expected.add("Deleted virtualenv: {}".format((venv_cache / name))) expected.add(f"Deleted virtualenv: {venv_cache / name}")
assert expected == set(tester.io.fetch_output().split("\n")) assert expected == set(tester.io.fetch_output().split("\n"))
...@@ -66,7 +64,7 @@ def test_remove_multiple(tester, venvs_in_cache_dirs, venv_name, venv_cache): ...@@ -66,7 +64,7 @@ def test_remove_multiple(tester, venvs_in_cache_dirs, venv_name, venv_cache):
tester.execute(" ".join(removed_envs)) tester.execute(" ".join(removed_envs))
for name in removed_envs: for name in removed_envs:
assert not (venv_cache / name).exists() assert not (venv_cache / name).exists()
expected.add("Deleted virtualenv: {}".format((venv_cache / name))) expected.add(f"Deleted virtualenv: {venv_cache / name}")
for name in remaining_envs: for name in remaining_envs:
assert (venv_cache / name).exists() assert (venv_cache / name).exists()
assert expected == set(tester.io.fetch_output().split("\n")) assert expected == set(tester.io.fetch_output().split("\n"))
...@@ -50,7 +50,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file( ...@@ -50,7 +50,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file(
tester.execute("3.7") tester.execute("3.7")
venv_py37 = venv_cache / "{}-py3.7".format(venv_name) venv_py37 = venv_cache / f"{venv_name}-py3.7"
mock_build_env.assert_called_with( mock_build_env.assert_called_with(
venv_py37, venv_py37,
executable="python3.7", executable="python3.7",
...@@ -85,7 +85,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var( ...@@ -85,7 +85,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
python_minor = ".".join(str(v) for v in current_python[:2]) python_minor = ".".join(str(v) for v in current_python[:2])
python_patch = ".".join(str(v) for v in current_python[:3]) python_patch = ".".join(str(v) for v in current_python[:3])
venv_dir = venv_cache / "{}-py{}".format(venv_name, python_minor) venv_dir = venv_cache / f"{venv_name}-py{python_minor}"
venv_dir.mkdir(parents=True, exist_ok=True) venv_dir.mkdir(parents=True, exist_ok=True)
envs_file = TOMLFile(venv_cache / "envs.toml") envs_file = TOMLFile(venv_cache / "envs.toml")
...@@ -110,7 +110,7 @@ def test_get_prefers_explicitly_activated_non_existing_virtualenvs_over_env_var( ...@@ -110,7 +110,7 @@ def test_get_prefers_explicitly_activated_non_existing_virtualenvs_over_env_var(
os.environ["VIRTUAL_ENV"] = "/environment/prefix" os.environ["VIRTUAL_ENV"] = "/environment/prefix"
python_minor = ".".join(str(v) for v in current_python[:2]) python_minor = ".".join(str(v) for v in current_python[:2])
venv_dir = venv_cache / "{}-py{}".format(venv_name, python_minor) venv_dir = venv_cache / f"{venv_name}-py{python_minor}"
mocker.patch( mocker.patch(
"poetry.utils.env.EnvManager._env", "poetry.utils.env.EnvManager._env",
......
...@@ -348,7 +348,7 @@ def test_add_directory_with_poetry(app, repo, tester, mocker): ...@@ -348,7 +348,7 @@ def test_add_directory_with_poetry(app, repo, tester, mocker):
repo.add_package(get_package("pendulum", "1.4.4")) repo.add_package(get_package("pendulum", "1.4.4"))
path = "../git/github.com/demo/pyproject-demo" path = "../git/github.com/demo/pyproject-demo"
tester.execute("{}".format(path)) tester.execute(f"{path}")
expected = """\ expected = """\
...@@ -376,7 +376,7 @@ def test_add_file_constraint_wheel(app, repo, tester, mocker, poetry): ...@@ -376,7 +376,7 @@ def test_add_file_constraint_wheel(app, repo, tester, mocker, poetry):
repo.add_package(get_package("pendulum", "1.4.4")) repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0-py2.py3-none-any.whl" path = "../distributions/demo-0.1.0-py2.py3-none-any.whl"
tester.execute("{}".format(path)) tester.execute(f"{path}")
expected = """\ expected = """\
...@@ -411,7 +411,7 @@ def test_add_file_constraint_sdist(app, repo, tester, mocker): ...@@ -411,7 +411,7 @@ def test_add_file_constraint_sdist(app, repo, tester, mocker):
repo.add_package(get_package("pendulum", "1.4.4")) repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0.tar.gz" path = "../distributions/demo-0.1.0.tar.gz"
tester.execute("{}".format(path)) tester.execute(f"{path}")
expected = """\ expected = """\
...@@ -586,7 +586,7 @@ def test_add_constraint_with_platform(app, repo, tester, env): ...@@ -586,7 +586,7 @@ def test_add_constraint_with_platform(app, repo, tester, env):
repo.add_package(get_package("cachy", "0.1.0")) repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(cachy2) repo.add_package(cachy2)
tester.execute("cachy=0.2.0 --platform {} -vvv".format(platform)) tester.execute(f"cachy=0.2.0 --platform {platform} -vvv")
expected = """\ expected = """\
...@@ -1144,7 +1144,7 @@ def test_add_directory_constraint_old_installer( ...@@ -1144,7 +1144,7 @@ def test_add_directory_constraint_old_installer(
repo.add_package(get_package("cleo", "0.6.5")) repo.add_package(get_package("cleo", "0.6.5"))
path = "../git/github.com/demo/demo" path = "../git/github.com/demo/demo"
old_tester.execute("{}".format(path)) old_tester.execute(f"{path}")
expected = """\ expected = """\
...@@ -1180,7 +1180,7 @@ def test_add_directory_with_poetry_old_installer( ...@@ -1180,7 +1180,7 @@ def test_add_directory_with_poetry_old_installer(
repo.add_package(get_package("pendulum", "1.4.4")) repo.add_package(get_package("pendulum", "1.4.4"))
path = "../git/github.com/demo/pyproject-demo" path = "../git/github.com/demo/pyproject-demo"
old_tester.execute("{}".format(path)) old_tester.execute(f"{path}")
expected = """\ expected = """\
...@@ -1211,7 +1211,7 @@ def test_add_file_constraint_wheel_old_installer( ...@@ -1211,7 +1211,7 @@ def test_add_file_constraint_wheel_old_installer(
repo.add_package(get_package("pendulum", "1.4.4")) repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0-py2.py3-none-any.whl" path = "../distributions/demo-0.1.0-py2.py3-none-any.whl"
old_tester.execute("{}".format(path)) old_tester.execute(f"{path}")
expected = """\ expected = """\
...@@ -1249,7 +1249,7 @@ def test_add_file_constraint_sdist_old_installer( ...@@ -1249,7 +1249,7 @@ def test_add_file_constraint_sdist_old_installer(
repo.add_package(get_package("pendulum", "1.4.4")) repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0.tar.gz" path = "../distributions/demo-0.1.0.tar.gz"
old_tester.execute("{}".format(path)) old_tester.execute(f"{path}")
expected = """\ expected = """\
...@@ -1435,7 +1435,7 @@ def test_add_constraint_with_platform_old_installer( ...@@ -1435,7 +1435,7 @@ def test_add_constraint_with_platform_old_installer(
repo.add_package(get_package("cachy", "0.1.0")) repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(cachy2) repo.add_package(cachy2)
old_tester.execute("cachy=0.2.0 --platform {} -vvv".format(platform)) old_tester.execute(f"cachy=0.2.0 --platform {platform} -vvv")
expected = """\ expected = """\
......
...@@ -16,12 +16,12 @@ def repository_cache_dir(monkeypatch, tmpdir): ...@@ -16,12 +16,12 @@ def repository_cache_dir(monkeypatch, tmpdir):
@pytest.fixture @pytest.fixture
def repository_one(): def repository_one():
return "01_{}".format(uuid.uuid4()) return f"01_{uuid.uuid4()}"
@pytest.fixture @pytest.fixture
def repository_two(): def repository_two():
return "02_{}".format(uuid.uuid4()) return f"02_{uuid.uuid4()}"
@pytest.fixture @pytest.fixture
......
...@@ -660,9 +660,7 @@ line-length = 88 ...@@ -660,9 +660,7 @@ line-length = 88
""" """
pyproject_file.write_text(decode(existing_section)) pyproject_file.write_text(decode(existing_section))
tester.execute(inputs=init_basic_inputs) tester.execute(inputs=init_basic_inputs)
assert ( assert f"{existing_section}\n{init_basic_toml}" in pyproject_file.read_text()
"{}\n{}".format(existing_section, init_basic_toml) in pyproject_file.read_text()
)
def test_init_non_interactive_existing_pyproject_add_dependency( def test_init_non_interactive_existing_pyproject_add_dependency(
...@@ -698,7 +696,7 @@ packages = [{include = "my_package"}] ...@@ -698,7 +696,7 @@ packages = [{include = "my_package"}]
python = "^3.6" python = "^3.6"
foo = "^1.19.2" foo = "^1.19.2"
""" """
assert "{}\n{}".format(existing_section, expected) in pyproject_file.read_text() assert f"{existing_section}\n{expected}" in pyproject_file.read_text()
def test_init_existing_pyproject_with_build_system_fails( def test_init_existing_pyproject_with_build_system_fails(
...@@ -716,4 +714,4 @@ build-backend = "setuptools.build_meta" ...@@ -716,4 +714,4 @@ build-backend = "setuptools.build_meta"
tester.io.fetch_output().strip() tester.io.fetch_output().strip()
== "A pyproject.toml file with a defined build-system already exists." == "A pyproject.toml file with a defined build-system already exists."
) )
assert "{}".format(existing_section) in pyproject_file.read_text() assert f"{existing_section}" in pyproject_file.read_text()
...@@ -148,7 +148,7 @@ def test_command_new_with_readme(fmt, tester, tmp_dir): ...@@ -148,7 +148,7 @@ def test_command_new_with_readme(fmt, tester, tmp_dir):
fmt = "md" fmt = "md"
package = "package" package = "package"
path = Path(tmp_dir) / package path = Path(tmp_dir) / package
options = ["--readme {}".format(fmt) if fmt else "md", path.as_posix()] options = [f"--readme {fmt}" if fmt else "md", path.as_posix()]
tester.execute(" ".join(options)) tester.execute(" ".join(options))
poetry = verify_project_directory(path, package, package, None) poetry = verify_project_directory(path, package, package, None)
......
...@@ -98,7 +98,7 @@ def mock_download(url, dest, **__): ...@@ -98,7 +98,7 @@ def mock_download(url, dest, **__):
class TestExecutor(Executor): class TestExecutor(Executor):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(TestExecutor, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self._installs = [] self._installs = []
self._updates = [] self._updates = []
...@@ -117,10 +117,10 @@ class TestExecutor(Executor): ...@@ -117,10 +117,10 @@ class TestExecutor(Executor):
return self._uninstalls return self._uninstalls
def _do_execute_operation(self, operation): def _do_execute_operation(self, operation):
super(TestExecutor, self)._do_execute_operation(operation) super()._do_execute_operation(operation)
if not operation.skipped: if not operation.skipped:
getattr(self, "_{}s".format(operation.job_type)).append(operation.package) getattr(self, f"_{operation.job_type}s").append(operation.package)
def _execute_install(self, operation): def _execute_install(self, operation):
return 0 return 0
...@@ -134,7 +134,7 @@ class TestExecutor(Executor): ...@@ -134,7 +134,7 @@ class TestExecutor(Executor):
class PoetryTestApplication(Application): class PoetryTestApplication(Application):
def __init__(self, poetry): def __init__(self, poetry):
super(PoetryTestApplication, self).__init__() super().__init__()
self._poetry = poetry self._poetry = poetry
def reset_poetry(self): def reset_poetry(self):
...@@ -178,7 +178,7 @@ class TestLocker(Locker): ...@@ -178,7 +178,7 @@ class TestLocker(Locker):
def _write_lock_data(self, data): def _write_lock_data(self, data):
if self._write: if self._write:
super(TestLocker, self)._write_lock_data(data) super()._write_lock_data(data)
self._locked = True self._locked = True
return return
...@@ -187,9 +187,9 @@ class TestLocker(Locker): ...@@ -187,9 +187,9 @@ class TestLocker(Locker):
class TestRepository(Repository): class TestRepository(Repository):
def find_packages(self, dependency): def find_packages(self, dependency):
packages = super(TestRepository, self).find_packages(dependency) packages = super().find_packages(dependency)
if len(packages) == 0: if len(packages) == 0:
raise PackageNotFound("Package [{}] not found.".format(dependency.name)) raise PackageNotFound(f"Package [{dependency.name}] not found.")
return packages return packages
......
...@@ -44,7 +44,7 @@ class Installer(BaseInstaller): ...@@ -44,7 +44,7 @@ class Installer(BaseInstaller):
class Executor(BaseExecutor): class Executor(BaseExecutor):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(Executor, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self._installs = [] self._installs = []
self._updates = [] self._updates = []
...@@ -63,10 +63,10 @@ class Executor(BaseExecutor): ...@@ -63,10 +63,10 @@ class Executor(BaseExecutor):
return self._uninstalls return self._uninstalls
def _do_execute_operation(self, operation): def _do_execute_operation(self, operation):
super(Executor, self)._do_execute_operation(operation) super()._do_execute_operation(operation)
if not operation.skipped: if not operation.skipped:
getattr(self, "_{}s".format(operation.job_type)).append(operation.package) getattr(self, f"_{operation.job_type}s").append(operation.package)
def _execute_install(self, operation): def _execute_install(self, operation):
return 0 return 0
...@@ -180,7 +180,7 @@ def installer(package, pool, locker, env, installed, config): ...@@ -180,7 +180,7 @@ def installer(package, pool, locker, env, installed, config):
def fixture(name): def fixture(name):
file = TOMLFile(Path(__file__).parent / "fixtures" / "{}.test".format(name)) file = TOMLFile(Path(__file__).parent / "fixtures" / f"{name}.test")
return json.loads(json.dumps(file.read())) return json.loads(json.dumps(file.read()))
......
...@@ -124,7 +124,7 @@ def installer(package, pool, locker, env, installed, config): ...@@ -124,7 +124,7 @@ def installer(package, pool, locker, env, installed, config):
def fixture(name): def fixture(name):
file = TOMLFile(Path(__file__).parent / "fixtures" / "{}.test".format(name)) file = TOMLFile(Path(__file__).parent / "fixtures" / f"{name}.test")
return file.read() return file.read()
......
...@@ -69,7 +69,7 @@ def test_requirement_source_type_url(): ...@@ -69,7 +69,7 @@ def test_requirement_source_type_url():
) )
result = installer.requirement(foo, formatted=True) result = installer.requirement(foo, formatted=True)
expected = "{}#egg={}".format(foo.source_url, foo.name) expected = f"{foo.source_url}#egg={foo.name}"
assert expected == result assert expected == result
......
...@@ -24,9 +24,7 @@ class MockRepository(LegacyRepository): ...@@ -24,9 +24,7 @@ class MockRepository(LegacyRepository):
FIXTURES = Path(__file__).parent / "fixtures" / "legacy" FIXTURES = Path(__file__).parent / "fixtures" / "legacy"
def __init__(self): def __init__(self):
super(MockRepository, self).__init__( super().__init__("legacy", url="http://legacy.foo.bar", disable_cache=True)
"legacy", url="http://legacy.foo.bar", disable_cache=True
)
def _get_page(self, endpoint): def _get_page(self, endpoint):
parts = endpoint.split("/") parts = endpoint.split("/")
...@@ -110,7 +108,7 @@ def test_get_package_information_skips_dependencies_with_invalid_constraints(): ...@@ -110,7 +108,7 @@ def test_get_package_information_skips_dependencies_with_invalid_constraints():
assert 25 == len(package.requires) assert 25 == len(package.requires)
assert sorted( assert sorted(
[r for r in package.requires if not r.is_optional()], key=lambda r: r.name (r for r in package.requires if not r.is_optional()), key=lambda r: r.name
) == [ ) == [
Dependency("configparser", "*"), Dependency("configparser", "*"),
Dependency("future", ">=0.14.0"), Dependency("future", ">=0.14.0"),
...@@ -323,9 +321,7 @@ def test_get_package_retrieves_packages_with_no_hashes(): ...@@ -323,9 +321,7 @@ def test_get_package_retrieves_packages_with_no_hashes():
class MockHttpRepository(LegacyRepository): class MockHttpRepository(LegacyRepository):
def __init__(self, endpoint_responses, http): def __init__(self, endpoint_responses, http):
base_url = "http://legacy.foo.bar" base_url = "http://legacy.foo.bar"
super(MockHttpRepository, self).__init__( super().__init__("legacy", url=base_url, disable_cache=True)
"legacy", url=base_url, disable_cache=True
)
for endpoint, response in endpoint_responses.items(): for endpoint, response in endpoint_responses.items():
url = base_url + endpoint url = base_url + endpoint
......
...@@ -21,9 +21,7 @@ class MockRepository(PyPiRepository): ...@@ -21,9 +21,7 @@ class MockRepository(PyPiRepository):
DIST_FIXTURES = Path(__file__).parent / "fixtures" / "pypi.org" / "dists" DIST_FIXTURES = Path(__file__).parent / "fixtures" / "pypi.org" / "dists"
def __init__(self, fallback=False): def __init__(self, fallback=False):
super(MockRepository, self).__init__( super().__init__(url="http://foo.bar", disable_cache=True, fallback=fallback)
url="http://foo.bar", disable_cache=True, fallback=fallback
)
def _get(self, url): def _get(self, url):
parts = url.split("/")[1:] parts = url.split("/")[1:]
...@@ -111,7 +109,7 @@ def test_fallback_on_downloading_packages(): ...@@ -111,7 +109,7 @@ def test_fallback_on_downloading_packages():
assert package.name == "jupyter" assert package.name == "jupyter"
assert len(package.requires) == 6 assert len(package.requires) == 6
dependency_names = sorted([dep.name for dep in package.requires]) dependency_names = sorted(dep.name for dep in package.requires)
assert dependency_names == [ assert dependency_names == [
"ipykernel", "ipykernel",
"ipywidgets", "ipywidgets",
...@@ -165,7 +163,7 @@ def test_pypi_repository_supports_reading_bz2_files(): ...@@ -165,7 +163,7 @@ def test_pypi_repository_supports_reading_bz2_files():
assert package.name == "twisted" assert package.name == "twisted"
assert 71 == len(package.requires) assert 71 == len(package.requires)
assert sorted( assert sorted(
[r for r in package.requires if not r.is_optional()], key=lambda r: r.name (r for r in package.requires if not r.is_optional()), key=lambda r: r.name
) == [ ) == [
Dependency("attrs", ">=17.4.0"), Dependency("attrs", ">=17.4.0"),
Dependency("Automat", ">=0.3.0"), Dependency("Automat", ">=0.3.0"),
......
...@@ -61,9 +61,9 @@ def _maintain_symlinks(symlink_type, base_path): ...@@ -61,9 +61,9 @@ def _maintain_symlinks(symlink_type, base_path):
try: try:
# Try the cache first because going from git checkout to sdist is the # Try the cache first because going from git checkout to sdist is the
# only time we know that we're going to cache correctly # only time we know that we're going to cache correctly
with open(SYMLINK_CACHE, "r") as f: with open(SYMLINK_CACHE) as f:
symlink_data = json.load(f) symlink_data = json.load(f)
except (IOError, OSError) as e: except OSError as e:
# IOError on py2, OSError on py3. Both have errno # IOError on py2, OSError on py3. Both have errno
if e.errno == 2: if e.errno == 2:
# SYMLINKS_CACHE doesn't exist. Fallback to trying to create the # SYMLINKS_CACHE doesn't exist. Fallback to trying to create the
...@@ -137,7 +137,7 @@ class SDistCommand(SDist): ...@@ -137,7 +137,7 @@ class SDistCommand(SDist):
def read_file(file_name): def read_file(file_name):
"""Read file and return its contents.""" """Read file and return its contents."""
with open(file_name, "r") as f: with open(file_name) as f:
return f.read() return f.read()
......
...@@ -5,10 +5,10 @@ from collections import OrderedDict ...@@ -5,10 +5,10 @@ from collections import OrderedDict
from setuptools import setup from setuptools import setup
with io.open("README.rst", "rt", encoding="utf8") as f: with open("README.rst", encoding="utf8") as f:
readme = f.read() readme = f.read()
with io.open("flask/__init__.py", "rt", encoding="utf8") as f: with open("flask/__init__.py", encoding="utf8") as f:
version = re.search(r"__version__ = \'(.*?)\'", f.read()).group(1) version = re.search(r"__version__ = \'(.*?)\'", f.read()).group(1)
setup( setup(
......
...@@ -18,7 +18,7 @@ AUTHOR_EMAIL = "xi@resolvent.net" ...@@ -18,7 +18,7 @@ AUTHOR_EMAIL = "xi@resolvent.net"
LICENSE = "MIT" LICENSE = "MIT"
PLATFORMS = "Any" PLATFORMS = "Any"
URL = "http://pyyaml.org/wiki/PyYAML" URL = "http://pyyaml.org/wiki/PyYAML"
DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION) DOWNLOAD_URL = f"http://pyyaml.org/download/pyyaml/{NAME}-{VERSION}.tar.gz"
CLASSIFIERS = [ CLASSIFIERS = [
"Development Status :: 5 - Production/Stable", "Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers", "Intended Audience :: Developers",
...@@ -185,7 +185,7 @@ class build_ext(_build_ext): ...@@ -185,7 +185,7 @@ class build_ext(_build_ext):
filenames.append(filename) filenames.append(filename)
base = os.path.splitext(filename)[0] base = os.path.splitext(filename)[0]
for ext in ["c", "h", "pyx", "pxd"]: for ext in ["c", "h", "pyx", "pxd"]:
filename = "%s.%s" % (base, ext) filename = f"{base}.{ext}"
if filename not in filenames and os.path.isfile(filename): if filename not in filenames and os.path.isfile(filename):
filenames.append(filename) filenames.append(filename)
return filenames return filenames
......
...@@ -171,7 +171,7 @@ def test_authenticator_falls_back_to_keyring_netloc( ...@@ -171,7 +171,7 @@ def test_authenticator_falls_back_to_keyring_netloc(
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") @pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")
def test_authenticator_request_retries_on_exception(mocker, config, http): def test_authenticator_request_retries_on_exception(mocker, config, http):
sleep = mocker.patch("time.sleep") sleep = mocker.patch("time.sleep")
sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4())) sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz"
content = str(uuid.uuid4()) content = str(uuid.uuid4())
seen = [] seen = []
...@@ -194,7 +194,7 @@ def test_authenticator_request_raises_exception_when_attempts_exhausted( ...@@ -194,7 +194,7 @@ def test_authenticator_request_raises_exception_when_attempts_exhausted(
mocker, config, http mocker, config, http
): ):
sleep = mocker.patch("time.sleep") sleep = mocker.patch("time.sleep")
sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4())) sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz"
def callback(*_, **__): def callback(*_, **__):
raise requests.exceptions.ConnectionError(str(uuid.uuid4())) raise requests.exceptions.ConnectionError(str(uuid.uuid4()))
...@@ -216,7 +216,7 @@ def test_authenticator_request_retries_on_status_code( ...@@ -216,7 +216,7 @@ def test_authenticator_request_retries_on_status_code(
mocker, config, http, status, attempts mocker, config, http, status, attempts
): ):
sleep = mocker.patch("time.sleep") sleep = mocker.patch("time.sleep")
sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4())) sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz"
content = str(uuid.uuid4()) content = str(uuid.uuid4())
def callback(request, uri, response_headers): def callback(request, uri, response_headers):
......
...@@ -40,7 +40,7 @@ print("nullpackage loaded"), ...@@ -40,7 +40,7 @@ print("nullpackage loaded"),
class MockVirtualEnv(VirtualEnv): class MockVirtualEnv(VirtualEnv):
def __init__(self, path, base=None, sys_path=None): def __init__(self, path, base=None, sys_path=None):
super(MockVirtualEnv, self).__init__(path, base=base) super().__init__(path, base=base)
self._sys_path = sys_path self._sys_path = sys_path
...@@ -49,7 +49,7 @@ class MockVirtualEnv(VirtualEnv): ...@@ -49,7 +49,7 @@ class MockVirtualEnv(VirtualEnv):
if self._sys_path is not None: if self._sys_path is not None:
return self._sys_path return self._sys_path
return super(MockVirtualEnv, self).sys_path return super().sys_path
@pytest.fixture() @pytest.fixture()
...@@ -82,7 +82,7 @@ def test_env_commands_with_spaces_in_their_arg_work_as_expected(tmp_dir, manager ...@@ -82,7 +82,7 @@ def test_env_commands_with_spaces_in_their_arg_work_as_expected(tmp_dir, manager
manager.build_venv(str(venv_path)) manager.build_venv(str(venv_path))
venv = VirtualEnv(venv_path) venv = VirtualEnv(venv_path)
assert venv.run("python", venv.pip, "--version", shell=True).startswith( assert venv.run("python", venv.pip, "--version", shell=True).startswith(
"pip {} from ".format(venv.pip_version) f"pip {venv.pip_version} from "
) )
...@@ -134,7 +134,7 @@ def check_output_wrapper(version=VERSION_3_7_1): ...@@ -134,7 +134,7 @@ def check_output_wrapper(version=VERSION_3_7_1):
if "sys.version_info[:3]" in cmd: if "sys.version_info[:3]" in cmd:
return version.text return version.text
elif "sys.version_info[:2]" in cmd: elif "sys.version_info[:2]" in cmd:
return "{}.{}".format(version.major, version.minor) return f"{version.major}.{version.minor}"
else: else:
return str(Path("/prefix")) return str(Path("/prefix"))
...@@ -163,7 +163,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file( ...@@ -163,7 +163,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file(
venv_name = EnvManager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = EnvManager.generate_env_name("simple-project", str(poetry.file.parent))
m.assert_called_with( m.assert_called_with(
Path(tmp_dir) / "{}-py3.7".format(venv_name), Path(tmp_dir) / f"{venv_name}-py3.7",
executable="python3.7", executable="python3.7",
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
...@@ -177,7 +177,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file( ...@@ -177,7 +177,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file(
assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1" assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix") assert env.base == Path("/prefix")
...@@ -189,7 +189,7 @@ def test_activate_activates_existing_virtualenv_no_envs_file( ...@@ -189,7 +189,7 @@ def test_activate_activates_existing_virtualenv_no_envs_file(
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
...@@ -213,7 +213,7 @@ def test_activate_activates_existing_virtualenv_no_envs_file( ...@@ -213,7 +213,7 @@ def test_activate_activates_existing_virtualenv_no_envs_file(
assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1" assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix") assert env.base == Path("/prefix")
...@@ -230,7 +230,7 @@ def test_activate_activates_same_virtualenv_with_envs_file( ...@@ -230,7 +230,7 @@ def test_activate_activates_same_virtualenv_with_envs_file(
doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"} doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"}
envs_file.write(doc) envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
...@@ -253,7 +253,7 @@ def test_activate_activates_same_virtualenv_with_envs_file( ...@@ -253,7 +253,7 @@ def test_activate_activates_same_virtualenv_with_envs_file(
assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1" assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix") assert env.base == Path("/prefix")
...@@ -269,7 +269,7 @@ def test_activate_activates_different_virtualenv_with_envs_file( ...@@ -269,7 +269,7 @@ def test_activate_activates_different_virtualenv_with_envs_file(
doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"} doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"}
envs_file.write(doc) envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
...@@ -286,7 +286,7 @@ def test_activate_activates_different_virtualenv_with_envs_file( ...@@ -286,7 +286,7 @@ def test_activate_activates_different_virtualenv_with_envs_file(
env = manager.activate("python3.6", NullIO()) env = manager.activate("python3.6", NullIO())
m.assert_called_with( m.assert_called_with(
Path(tmp_dir) / "{}-py3.6".format(venv_name), Path(tmp_dir) / f"{venv_name}-py3.6",
executable="python3.6", executable="python3.6",
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
...@@ -299,7 +299,7 @@ def test_activate_activates_different_virtualenv_with_envs_file( ...@@ -299,7 +299,7 @@ def test_activate_activates_different_virtualenv_with_envs_file(
assert envs[venv_name]["minor"] == "3.6" assert envs[venv_name]["minor"] == "3.6"
assert envs[venv_name]["patch"] == "3.6.6" assert envs[venv_name]["patch"] == "3.6.6"
assert env.path == Path(tmp_dir) / "{}-py3.6".format(venv_name) assert env.path == Path(tmp_dir) / f"{venv_name}-py3.6"
assert env.base == Path("/prefix") assert env.base == Path("/prefix")
...@@ -315,7 +315,7 @@ def test_activate_activates_recreates_for_different_patch( ...@@ -315,7 +315,7 @@ def test_activate_activates_recreates_for_different_patch(
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"} doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
envs_file.write(doc) envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
...@@ -343,23 +343,23 @@ def test_activate_activates_recreates_for_different_patch( ...@@ -343,23 +343,23 @@ def test_activate_activates_recreates_for_different_patch(
env = manager.activate("python3.7", NullIO()) env = manager.activate("python3.7", NullIO())
build_venv_m.assert_called_with( build_venv_m.assert_called_with(
Path(tmp_dir) / "{}-py3.7".format(venv_name), Path(tmp_dir) / f"{venv_name}-py3.7",
executable="python3.7", executable="python3.7",
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
with_setuptools=True, with_setuptools=True,
with_wheel=True, with_wheel=True,
) )
remove_venv_m.assert_called_with(Path(tmp_dir) / "{}-py3.7".format(venv_name)) remove_venv_m.assert_called_with(Path(tmp_dir) / f"{venv_name}-py3.7")
assert envs_file.exists() assert envs_file.exists()
envs = envs_file.read() envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1" assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix") assert env.base == Path("/prefix")
assert (Path(tmp_dir) / "{}-py3.7".format(venv_name)).exists() assert (Path(tmp_dir) / f"{venv_name}-py3.7").exists()
def test_activate_does_not_recreate_when_switching_minor( def test_activate_does_not_recreate_when_switching_minor(
...@@ -374,8 +374,8 @@ def test_activate_does_not_recreate_when_switching_minor( ...@@ -374,8 +374,8 @@ def test_activate_does_not_recreate_when_switching_minor(
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"} doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
envs_file.write(doc) envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
os.mkdir(os.path.join(tmp_dir, "{}-py3.6".format(venv_name))) os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.6"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
...@@ -404,9 +404,9 @@ def test_activate_does_not_recreate_when_switching_minor( ...@@ -404,9 +404,9 @@ def test_activate_does_not_recreate_when_switching_minor(
assert envs[venv_name]["minor"] == "3.6" assert envs[venv_name]["minor"] == "3.6"
assert envs[venv_name]["patch"] == "3.6.6" assert envs[venv_name]["patch"] == "3.6.6"
assert env.path == Path(tmp_dir) / "{}-py3.6".format(venv_name) assert env.path == Path(tmp_dir) / f"{venv_name}-py3.6"
assert env.base == Path("/prefix") assert env.base == Path("/prefix")
assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() assert (Path(tmp_dir) / f"{venv_name}-py3.6").exists()
def test_deactivate_non_activated_but_existing( def test_deactivate_non_activated_but_existing(
...@@ -445,18 +445,15 @@ def test_deactivate_activated(tmp_dir, manager, poetry, config, mocker): ...@@ -445,18 +445,15 @@ def test_deactivate_activated(tmp_dir, manager, poetry, config, mocker):
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
version = Version.parse(".".join(str(c) for c in sys.version_info[:3])) version = Version.parse(".".join(str(c) for c in sys.version_info[:3]))
other_version = Version.parse("3.4") if version.major == 2 else version.next_minor() other_version = Version.parse("3.4") if version.major == 2 else version.next_minor()
(Path(tmp_dir) / f"{venv_name}-py{version.major}.{version.minor}").mkdir()
( (
Path(tmp_dir) / "{}-py{}.{}".format(venv_name, version.major, version.minor) Path(tmp_dir) / f"{venv_name}-py{other_version.major}.{other_version.minor}"
).mkdir()
(
Path(tmp_dir)
/ "{}-py{}.{}".format(venv_name, other_version.major, other_version.minor)
).mkdir() ).mkdir()
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml") envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document() doc = tomlkit.document()
doc[venv_name] = { doc[venv_name] = {
"minor": "{}.{}".format(other_version.major, other_version.minor), "minor": f"{other_version.major}.{other_version.minor}",
"patch": other_version.text, "patch": other_version.text,
} }
envs_file.write(doc) envs_file.write(doc)
...@@ -488,7 +485,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var( ...@@ -488,7 +485,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
(Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml") envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document() doc = tomlkit.document()
...@@ -506,7 +503,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var( ...@@ -506,7 +503,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
env = manager.get() env = manager.get()
assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix") assert env.base == Path("/prefix")
...@@ -514,22 +511,22 @@ def test_list(tmp_dir, manager, poetry, config): ...@@ -514,22 +511,22 @@ def test_list(tmp_dir, manager, poetry, config):
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
venvs = manager.list() venvs = manager.list()
assert 2 == len(venvs) assert 2 == len(venvs)
assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venvs[0].path assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venvs[0].path
assert (Path(tmp_dir) / "{}-py3.7".format(venv_name)) == venvs[1].path assert (Path(tmp_dir) / f"{venv_name}-py3.7") == venvs[1].path
def test_remove_by_python_version(tmp_dir, manager, poetry, config, mocker): def test_remove_by_python_version(tmp_dir, manager, poetry, config, mocker):
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
mocker.patch( mocker.patch(
"subprocess.check_output", "subprocess.check_output",
...@@ -538,34 +535,34 @@ def test_remove_by_python_version(tmp_dir, manager, poetry, config, mocker): ...@@ -538,34 +535,34 @@ def test_remove_by_python_version(tmp_dir, manager, poetry, config, mocker):
venv = manager.remove("3.6") venv = manager.remove("3.6")
assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venv.path assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venv.path
assert not (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() assert not (Path(tmp_dir) / f"{venv_name}-py3.6").exists()
def test_remove_by_name(tmp_dir, manager, poetry, config, mocker): def test_remove_by_name(tmp_dir, manager, poetry, config, mocker):
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
mocker.patch( mocker.patch(
"subprocess.check_output", "subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")), side_effect=check_output_wrapper(Version.parse("3.6.6")),
) )
venv = manager.remove("{}-py3.6".format(venv_name)) venv = manager.remove(f"{venv_name}-py3.6")
assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venv.path assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venv.path
assert not (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() assert not (Path(tmp_dir) / f"{venv_name}-py3.6").exists()
def test_remove_also_deactivates(tmp_dir, manager, poetry, config, mocker): def test_remove_also_deactivates(tmp_dir, manager, poetry, config, mocker):
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
mocker.patch( mocker.patch(
"subprocess.check_output", "subprocess.check_output",
...@@ -579,8 +576,8 @@ def test_remove_also_deactivates(tmp_dir, manager, poetry, config, mocker): ...@@ -579,8 +576,8 @@ def test_remove_also_deactivates(tmp_dir, manager, poetry, config, mocker):
venv = manager.remove("python3.6") venv = manager.remove("python3.6")
assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venv.path assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venv.path
assert not (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() assert not (Path(tmp_dir) / f"{venv_name}-py3.6").exists()
envs = envs_file.read() envs = envs_file.read()
assert venv_name not in envs assert venv_name not in envs
...@@ -592,7 +589,7 @@ def test_remove_keeps_dir_if_not_deleteable(tmp_dir, manager, poetry, config, mo ...@@ -592,7 +589,7 @@ def test_remove_keeps_dir_if_not_deleteable(tmp_dir, manager, poetry, config, mo
config.merge({"virtualenvs": {"path": str(tmp_dir)}}) config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
venv_path = Path(tmp_dir) / "{}-py3.6".format(venv_name) venv_path = Path(tmp_dir) / f"{venv_name}-py3.6"
venv_path.mkdir() venv_path.mkdir()
folder1_path = venv_path / "folder1" folder1_path = venv_path / "folder1"
...@@ -619,7 +616,7 @@ def test_remove_keeps_dir_if_not_deleteable(tmp_dir, manager, poetry, config, mo ...@@ -619,7 +616,7 @@ def test_remove_keeps_dir_if_not_deleteable(tmp_dir, manager, poetry, config, mo
m = mocker.patch("shutil.rmtree", side_effect=err_on_rm_venv_only) m = mocker.patch("shutil.rmtree", side_effect=err_on_rm_venv_only)
venv = manager.remove("{}-py3.6".format(venv_name)) venv = manager.remove(f"{venv_name}-py3.6")
m.assert_any_call(str(venv_path)) m.assert_any_call(str(venv_path))
...@@ -726,7 +723,7 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_generic_ ...@@ -726,7 +723,7 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_generic_
manager.create_venv(NullIO()) manager.create_venv(NullIO())
m.assert_called_with( m.assert_called_with(
config_virtualenvs_path / "{}-py3.7".format(venv_name), config_virtualenvs_path / f"{venv_name}-py3.7",
executable="python3", executable="python3",
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
...@@ -753,7 +750,7 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_specific ...@@ -753,7 +750,7 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_specific
manager.create_venv(NullIO()) manager.create_venv(NullIO())
m.assert_called_with( m.assert_called_with(
config_virtualenvs_path / "{}-py3.9".format(venv_name), config_virtualenvs_path / f"{venv_name}-py3.9",
executable="python3.9", executable="python3.9",
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
...@@ -839,8 +836,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility( ...@@ -839,8 +836,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility(
assert not check_output.called assert not check_output.called
m.assert_called_with( m.assert_called_with(
config_virtualenvs_path config_virtualenvs_path / f"{venv_name}-py{version.major}.{version.minor}",
/ "{}-py{}.{}".format(venv_name, version.major, version.minor),
executable=None, executable=None,
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
...@@ -864,7 +860,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable( ...@@ -864,7 +860,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable(
check_output = mocker.patch( check_output = mocker.patch(
"subprocess.check_output", "subprocess.check_output",
side_effect=check_output_wrapper( side_effect=check_output_wrapper(
Version.parse("{}.{}.0".format(version.major, version.minor - 1)) Version.parse(f"{version.major}.{version.minor - 1}.0")
), ),
) )
m = mocker.patch( m = mocker.patch(
...@@ -872,14 +868,13 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable( ...@@ -872,14 +868,13 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable(
) )
manager.create_venv( manager.create_venv(
NullIO(), executable="python{}.{}".format(version.major, version.minor - 1) NullIO(), executable=f"python{version.major}.{version.minor - 1}"
) )
assert check_output.called assert check_output.called
m.assert_called_with( m.assert_called_with(
config_virtualenvs_path config_virtualenvs_path / f"{venv_name}-py{version.major}.{version.minor - 1}",
/ "{}-py{}.{}".format(venv_name, version.major, version.minor - 1), executable=f"python{version.major}.{version.minor - 1}",
executable="python{}.{}".format(version.major, version.minor - 1),
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
with_setuptools=True, with_setuptools=True,
...@@ -1118,7 +1113,7 @@ def test_create_venv_accepts_fallback_version_w_nonzero_patchlevel( ...@@ -1118,7 +1113,7 @@ def test_create_venv_accepts_fallback_version_w_nonzero_patchlevel(
assert check_output.called assert check_output.called
m.assert_called_with( m.assert_called_with(
config_virtualenvs_path / "{}-py3.5".format(venv_name), config_virtualenvs_path / f"{venv_name}-py3.5",
executable="python3.5", executable="python3.5",
flags={"always-copy": False, "system-site-packages": False}, flags={"always-copy": False, "system-site-packages": False},
with_pip=True, with_pip=True,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment