diff --git a/.flake8 b/.flake8
index 84490393cf2..e0107ae7ae9 100644
--- a/.flake8
+++ b/.flake8
@@ -8,7 +8,7 @@ inline-quotes = double
# Allow omission of a return type hint for __init__ if at least one argument is annotated
# used by flake8-annotations
mypy-init-return = true
-enable-extensions = TC, TC2
+enable-extensions = TC, TC1
type-checking-exempt-modules = typing, typing-extensions
eradicate-whitelist-extend = ^-.*;
extend-ignore =
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 6ad55884126..5b40f3f7c64 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -50,7 +50,7 @@ repos:
hooks:
- id: pyupgrade
args: [--py37-plus]
- exclude: '^(install|get)-poetry.py$'
+ exclude: ^(install|get)-poetry.py$
- repo: https://github.com/pycqa/isort
rev: 5.10.1
@@ -58,6 +58,8 @@ repos:
- id: isort
name: "isort (python)"
types: [python]
+ args: [--add-import, from __future__ import annotations]
+ exclude: ^(install|get)-poetry.py$
- id: isort
name: "isort (pyi)"
types: [pyi]
diff --git a/src/poetry/__init__.py b/src/poetry/__init__.py
index 8db66d3d0f0..9e041d50b7d 100644
--- a/src/poetry/__init__.py
+++ b/src/poetry/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
diff --git a/src/poetry/__main__.py b/src/poetry/__main__.py
index 77e9947cd59..5ae15783302 100644
--- a/src/poetry/__main__.py
+++ b/src/poetry/__main__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import sys
diff --git a/src/poetry/__version__.py b/src/poetry/__version__.py
index 866c89d6de1..f912eb6596b 100644
--- a/src/poetry/__version__.py
+++ b/src/poetry/__version__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "1.2.0a2"
diff --git a/src/poetry/config/config.py b/src/poetry/config/config.py
index bf4898bfdd5..ec6f34bb338 100644
--- a/src/poetry/config/config.py
+++ b/src/poetry/config/config.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import re
@@ -6,8 +8,6 @@
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
-from typing import Dict
-from typing import Optional
from poetry.config.dict_config_source import DictConfigSource
from poetry.locations import CACHE_DIR
@@ -31,7 +31,7 @@ def int_normalizer(val: str) -> int:
class Config:
- default_config: Dict[str, Any] = {
+ default_config: dict[str, Any] = {
"cache-dir": str(CACHE_DIR),
"virtualenvs": {
"create": True,
@@ -45,43 +45,43 @@ class Config:
}
def __init__(
- self, use_environment: bool = True, base_dir: Optional[Path] = None
+ self, use_environment: bool = True, base_dir: Path | None = None
) -> None:
self._config = deepcopy(self.default_config)
self._use_environment = use_environment
self._base_dir = base_dir
- self._config_source: "ConfigSource" = DictConfigSource()
- self._auth_config_source: "ConfigSource" = DictConfigSource()
+ self._config_source: ConfigSource = DictConfigSource()
+ self._auth_config_source: ConfigSource = DictConfigSource()
@property
- def config(self) -> Dict:
+ def config(self) -> dict:
return self._config
@property
- def config_source(self) -> "ConfigSource":
+ def config_source(self) -> ConfigSource:
return self._config_source
@property
- def auth_config_source(self) -> "ConfigSource":
+ def auth_config_source(self) -> ConfigSource:
return self._auth_config_source
- def set_config_source(self, config_source: "ConfigSource") -> "Config":
+ def set_config_source(self, config_source: ConfigSource) -> Config:
self._config_source = config_source
return self
- def set_auth_config_source(self, config_source: "ConfigSource") -> "Config":
+ def set_auth_config_source(self, config_source: ConfigSource) -> Config:
self._auth_config_source = config_source
return self
- def merge(self, config: Dict[str, Any]) -> None:
+ def merge(self, config: dict[str, Any]) -> None:
from poetry.utils.helpers import merge_dicts
merge_dicts(self._config, config)
- def all(self) -> Dict[str, Any]:
- def _all(config: Dict, parent_key: str = "") -> Dict:
+ def all(self) -> dict[str, Any]:
+ def _all(config: dict, parent_key: str = "") -> dict:
all_ = {}
for key in config:
@@ -100,7 +100,7 @@ def _all(config: Dict, parent_key: str = "") -> Dict:
return _all(self.config)
- def raw(self) -> Dict[str, Any]:
+ def raw(self) -> dict[str, Any]:
return self._config
def get(self, setting_name: str, default: Any = None) -> Any:
diff --git a/src/poetry/config/config_source.py b/src/poetry/config/config_source.py
index 2fc9b585ac6..ed97fa9176a 100644
--- a/src/poetry/config/config_source.py
+++ b/src/poetry/config/config_source.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import Any
diff --git a/src/poetry/config/dict_config_source.py b/src/poetry/config/dict_config_source.py
index a279852e209..942d76ea1b4 100644
--- a/src/poetry/config/dict_config_source.py
+++ b/src/poetry/config/dict_config_source.py
@@ -1,15 +1,16 @@
+from __future__ import annotations
+
from typing import Any
-from typing import Dict
from poetry.config.config_source import ConfigSource
class DictConfigSource(ConfigSource):
def __init__(self) -> None:
- self._config: Dict[str, Any] = {}
+ self._config: dict[str, Any] = {}
@property
- def config(self) -> Dict[str, Any]:
+ def config(self) -> dict[str, Any]:
return self._config
def add_property(self, key: str, value: Any) -> None:
diff --git a/src/poetry/config/file_config_source.py b/src/poetry/config/file_config_source.py
index f1cc3ebf4e7..5d8584a8c57 100644
--- a/src/poetry/config/file_config_source.py
+++ b/src/poetry/config/file_config_source.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from contextlib import contextmanager
from typing import TYPE_CHECKING
from typing import Any
@@ -15,7 +17,7 @@
class FileConfigSource(ConfigSource):
- def __init__(self, file: "TOMLFile", auth_config: bool = False) -> None:
+ def __init__(self, file: TOMLFile, auth_config: bool = False) -> None:
self._file = file
self._auth_config = auth_config
@@ -24,7 +26,7 @@ def name(self) -> str:
return str(self._file.path)
@property
- def file(self) -> "TOMLFile":
+ def file(self) -> TOMLFile:
return self._file
def add_property(self, key: str, value: Any) -> None:
@@ -58,7 +60,7 @@ def remove_property(self, key: str) -> None:
current_config = current_config[key]
@contextmanager
- def secure(self) -> Iterator["TOMLDocument"]:
+ def secure(self) -> Iterator[TOMLDocument]:
if self.file.exists():
initial_config = self.file.read()
config = self.file.read()
diff --git a/src/poetry/config/source.py b/src/poetry/config/source.py
index 3735b193dfa..f3af0c589e2 100644
--- a/src/poetry/config/source.py
+++ b/src/poetry/config/source.py
@@ -1,7 +1,6 @@
-import dataclasses
+from __future__ import annotations
-from typing import Dict
-from typing import Union
+import dataclasses
@dataclasses.dataclass(order=True, eq=True)
@@ -11,5 +10,5 @@ class Source:
default: bool = dataclasses.field(default=False)
secondary: bool = dataclasses.field(default=False)
- def to_dict(self) -> Dict[str, Union[str, bool]]:
+ def to_dict(self) -> dict[str, str | bool]:
return dataclasses.asdict(self)
diff --git a/src/poetry/console/application.py b/src/poetry/console/application.py
index 96f2e953cf5..1d17c55d805 100644
--- a/src/poetry/console/application.py
+++ b/src/poetry/console/application.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import logging
import re
@@ -6,8 +8,6 @@
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
-from typing import Optional
-from typing import Type
from typing import cast
from cleo.application import Application as BaseApplication
@@ -37,7 +37,7 @@
def load_command(name: str) -> Callable:
- def _load() -> Type[Command]:
+ def _load() -> type[Command]:
words = name.split(" ")
module = import_module("poetry.console.commands." + ".".join(words))
command_class = getattr(module, "".join(c.title() for c in words) + "Command")
@@ -94,7 +94,7 @@ def __init__(self) -> None:
super().__init__("poetry", __version__)
self._poetry = None
- self._io: Optional["IO"] = None
+ self._io: IO | None = None
self._disable_plugins = False
self._plugins_loaded = False
@@ -108,7 +108,7 @@ def __init__(self) -> None:
self.set_command_loader(command_loader)
@property
- def poetry(self) -> "Poetry":
+ def poetry(self) -> Poetry:
from pathlib import Path
from poetry.factory import Factory
@@ -131,10 +131,10 @@ def reset_poetry(self) -> None:
def create_io(
self,
- input: Optional["Input"] = None,
- output: Optional["Output"] = None,
- error_output: Optional["Output"] = None,
- ) -> "IO":
+ input: Input | None = None,
+ output: Output | None = None,
+ error_output: Output | None = None,
+ ) -> IO:
io = super().create_io(input, output, error_output)
# Set our own CLI styles
@@ -159,21 +159,21 @@ def create_io(
return io
- def render_error(self, error: Exception, io: "IO") -> None:
+ def render_error(self, error: Exception, io: IO) -> None:
# We set the solution provider repository here to load providers
# only when an error occurs
self.set_solution_provider_repository(self._get_solution_provider_repository())
super().render_error(error, io)
- def _run(self, io: "IO") -> int:
+ def _run(self, io: IO) -> int:
self._disable_plugins = io.input.parameter_option("--no-plugins")
self._load_plugins(io)
return super()._run(io)
- def _configure_io(self, io: "IO") -> None:
+ def _configure_io(self, io: IO) -> None:
# We need to check if the command being run
# is the "run" command.
definition = self.definition
@@ -210,7 +210,7 @@ def _configure_io(self, io: "IO") -> None:
return super()._configure_io(io)
def register_command_loggers(
- self, event: "ConsoleCommandEvent", event_name: str, _: Any
+ self, event: ConsoleCommandEvent, event_name: str, _: Any
) -> None:
from poetry.console.logging.io_formatter import IOFormatter
from poetry.console.logging.io_handler import IOHandler
@@ -251,7 +251,7 @@ def register_command_loggers(
logger.setLevel(level)
def configure_env(
- self, event: "ConsoleCommandEvent", event_name: str, _: Any
+ self, event: ConsoleCommandEvent, event_name: str, _: Any
) -> None:
from poetry.console.commands.env_command import EnvCommand
@@ -276,11 +276,11 @@ def configure_env(
command.set_env(env)
def configure_installer(
- self, event: "ConsoleCommandEvent", event_name: str, _: Any
+ self, event: ConsoleCommandEvent, event_name: str, _: Any
) -> None:
from poetry.console.commands.installer_command import InstallerCommand
- command: "InstallerCommand" = cast(InstallerCommand, event.command)
+ command: InstallerCommand = cast(InstallerCommand, event.command)
if not isinstance(command, InstallerCommand):
return
@@ -291,7 +291,7 @@ def configure_installer(
self._configure_installer(command, event.io)
- def _configure_installer(self, command: "InstallerCommand", io: "IO") -> None:
+ def _configure_installer(self, command: InstallerCommand, io: IO) -> None:
from poetry.installation.installer import Installer
poetry = command.poetry
@@ -306,7 +306,7 @@ def _configure_installer(self, command: "InstallerCommand", io: "IO") -> None:
installer.use_executor(poetry.config.get("experimental.new-installer", False))
command.set_installer(installer)
- def _load_plugins(self, io: "IO") -> None:
+ def _load_plugins(self, io: IO) -> None:
if self._plugins_loaded:
return
@@ -322,7 +322,7 @@ def _load_plugins(self, io: "IO") -> None:
self._plugins_loaded = True
@property
- def _default_definition(self) -> "Definition":
+ def _default_definition(self) -> Definition:
from cleo.io.inputs.option import Option
definition = super()._default_definition
@@ -333,7 +333,7 @@ def _default_definition(self) -> "Definition":
return definition
- def _get_solution_provider_repository(self) -> "SolutionProviderRepository":
+ def _get_solution_provider_repository(self) -> SolutionProviderRepository:
from crashtest.solution_providers.solution_provider_repository import (
SolutionProviderRepository,
)
diff --git a/src/poetry/console/command_loader.py b/src/poetry/console/command_loader.py
index 852abe07dc6..91485766f01 100644
--- a/src/poetry/console/command_loader.py
+++ b/src/poetry/console/command_loader.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import Callable
from cleo.exceptions import LogicException
diff --git a/src/poetry/console/commands/about.py b/src/poetry/console/commands/about.py
index 18ef62a78af..678f555b4f6 100644
--- a/src/poetry/console/commands/about.py
+++ b/src/poetry/console/commands/about.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.console.commands.command import Command
diff --git a/src/poetry/console/commands/add.py b/src/poetry/console/commands/add.py
index 49d960a85d3..854bcb91803 100644
--- a/src/poetry/console/commands/add.py
+++ b/src/poetry/console/commands/add.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
import contextlib
-from typing import Dict
-from typing import List
from typing import cast
from cleo.helpers import argument
@@ -246,8 +246,8 @@ def handle(self) -> int:
return status
def get_existing_packages_from_input(
- self, packages: List[str], section: Dict
- ) -> List[str]:
+ self, packages: list[str], section: dict
+ ) -> list[str]:
existing_packages = []
for name in packages:
@@ -257,7 +257,7 @@ def get_existing_packages_from_input(
return existing_packages
- def notify_about_existing_packages(self, existing_packages: List[str]) -> None:
+ def notify_about_existing_packages(self, existing_packages: list[str]) -> None:
self.line(
"The following packages are already present in the pyproject.toml and will"
" be skipped:\n"
diff --git a/src/poetry/console/commands/build.py b/src/poetry/console/commands/build.py
index dfbfa11b1ca..9d5545326ca 100644
--- a/src/poetry/console/commands/build.py
+++ b/src/poetry/console/commands/build.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import option
from poetry.console.commands.env_command import EnvCommand
diff --git a/src/poetry/console/commands/cache/clear.py b/src/poetry/console/commands/cache/clear.py
index dee6a838e18..9c2c19b194c 100644
--- a/src/poetry/console/commands/cache/clear.py
+++ b/src/poetry/console/commands/cache/clear.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
from cleo.helpers import argument
diff --git a/src/poetry/console/commands/cache/list.py b/src/poetry/console/commands/cache/list.py
index f861b3e0be7..5dc835699a9 100644
--- a/src/poetry/console/commands/cache/list.py
+++ b/src/poetry/console/commands/cache/list.py
@@ -1,6 +1,6 @@
-import os
+from __future__ import annotations
-from typing import Optional
+import os
from poetry.console.commands.command import Command
@@ -10,7 +10,7 @@ class CacheListCommand(Command):
name = "cache list"
description = "List Poetry's caches."
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
from poetry.locations import REPOSITORY_CACHE_DIR
if os.path.exists(str(REPOSITORY_CACHE_DIR)):
diff --git a/src/poetry/console/commands/check.py b/src/poetry/console/commands/check.py
index 28d83b7cb89..8547305effe 100644
--- a/src/poetry/console/commands/check.py
+++ b/src/poetry/console/commands/check.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from pathlib import Path
from poetry.console.commands.command import Command
diff --git a/src/poetry/console/commands/command.py b/src/poetry/console/commands/command.py
index a812311931e..89fca111639 100644
--- a/src/poetry/console/commands/command.py
+++ b/src/poetry/console/commands/command.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
from cleo.commands.command import Command as BaseCommand
@@ -11,21 +11,21 @@
class Command(BaseCommand):
- loggers: List[str] = []
+ loggers: list[str] = []
- _poetry: Optional["Poetry"] = None
+ _poetry: Poetry | None = None
@property
- def poetry(self) -> "Poetry":
+ def poetry(self) -> Poetry:
if self._poetry is None:
return self.get_application().poetry
return self._poetry
- def set_poetry(self, poetry: "Poetry") -> None:
+ def set_poetry(self, poetry: Poetry) -> None:
self._poetry = poetry
- def get_application(self) -> "Application":
+ def get_application(self) -> Application:
return self.application
def reset_poetry(self) -> None:
diff --git a/src/poetry/console/commands/config.py b/src/poetry/console/commands/config.py
index 5dcc4c39acb..058e0560284 100644
--- a/src/poetry/console/commands/config.py
+++ b/src/poetry/console/commands/config.py
@@ -1,13 +1,10 @@
+from __future__ import annotations
+
import json
import re
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Tuple
-from typing import Union
from typing import cast
from cleo.helpers import argument
@@ -49,7 +46,7 @@ class ConfigCommand(Command):
LIST_PROHIBITED_SETTINGS = {"http-basic", "pypi-token"}
@property
- def unique_config_values(self) -> Dict[str, Tuple[Any, Any, Any]]:
+ def unique_config_values(self) -> dict[str, tuple[Any, Any, Any]]:
from pathlib import Path
from poetry.config.config import boolean_normalizer
@@ -104,7 +101,7 @@ def unique_config_values(self) -> Dict[str, Tuple[Any, Any, Any]]:
return unique_config_values
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
from pathlib import Path
from poetry.core.pyproject.exceptions import PyProjectException
@@ -146,7 +143,7 @@ def handle(self) -> Optional[int]:
# show the value if no value is provided
if not self.argument("value") and not self.option("unset"):
m = re.match(r"^repos?(?:itories)?(?:\.(.+))?", self.argument("key"))
- value: Union[str, Dict[str, Any]]
+ value: str | dict[str, Any]
if m:
if not m.group(1):
value = {}
@@ -173,7 +170,7 @@ def handle(self) -> Optional[int]:
return 0
- values: List[str] = self.argument("value")
+ values: list[str] = self.argument("value")
unique_config_values = self.unique_config_values
if setting_key in unique_config_values:
@@ -281,10 +278,10 @@ def handle(self) -> Optional[int]:
def _handle_single_value(
self,
- source: "ConfigSource",
+ source: ConfigSource,
key: str,
- callbacks: Tuple[Any, Any, Any],
- values: List[Any],
+ callbacks: tuple[Any, Any, Any],
+ values: list[Any],
) -> int:
validator, normalizer, _ = callbacks
@@ -300,7 +297,7 @@ def _handle_single_value(
return 0
def _list_configuration(
- self, config: Dict[str, Any], raw: Dict[str, Any], k: str = ""
+ self, config: dict[str, Any], raw: dict[str, Any], k: str = ""
) -> None:
orig_k = k
for key, value in sorted(config.items()):
@@ -334,11 +331,11 @@ def _list_configuration(
def _get_setting(
self,
- contents: Dict,
- setting: Optional[str] = None,
- k: Optional[str] = None,
- default: Optional[Any] = None,
- ) -> List[Tuple[str, str]]:
+ contents: dict,
+ setting: str | None = None,
+ k: str | None = None,
+ default: Any | None = None,
+ ) -> list[tuple[str, str]]:
orig_k = k
if setting and setting.split(".")[0] not in contents:
diff --git a/src/poetry/console/commands/debug/info.py b/src/poetry/console/commands/debug/info.py
index cbfbf1402db..bc062b118df 100644
--- a/src/poetry/console/commands/debug/info.py
+++ b/src/poetry/console/commands/debug/info.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import sys
from poetry.console.commands.command import Command
diff --git a/src/poetry/console/commands/debug/resolve.py b/src/poetry/console/commands/debug/resolve.py
index cb2948b0f8d..87a4f07f533 100644
--- a/src/poetry/console/commands/debug/resolve.py
+++ b/src/poetry/console/commands/debug/resolve.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from cleo.helpers import argument
@@ -92,7 +94,7 @@ def handle(self) -> int:
self.line("")
if self.option("tree"):
- show_command: "ShowCommand" = self.application.find("show")
+ show_command: ShowCommand = self.application.find("show")
show_command.init_styles(self.io)
packages = [op.package for op in ops]
diff --git a/src/poetry/console/commands/env/info.py b/src/poetry/console/commands/env/info.py
index ce0e52064c5..d3f5a309022 100644
--- a/src/poetry/console/commands/env/info.py
+++ b/src/poetry/console/commands/env/info.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
from cleo.helpers import option
@@ -17,7 +18,7 @@ class EnvInfoCommand(Command):
options = [option("path", "p", "Only display the environment's path.")]
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
from poetry.utils.env import EnvManager
env = EnvManager(self.poetry).get()
@@ -33,7 +34,7 @@ def handle(self) -> Optional[int]:
self._display_complete_info(env)
return None
- def _display_complete_info(self, env: "Env") -> None:
+ def _display_complete_info(self, env: Env) -> None:
env_python_version = ".".join(str(s) for s in env.version_info[:3])
self.line("")
self.line("Virtualenv")
diff --git a/src/poetry/console/commands/env/list.py b/src/poetry/console/commands/env/list.py
index a6f1fb91cfe..f2e51d94e72 100644
--- a/src/poetry/console/commands/env/list.py
+++ b/src/poetry/console/commands/env/list.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import option
from poetry.console.commands.command import Command
diff --git a/src/poetry/console/commands/env/remove.py b/src/poetry/console/commands/env/remove.py
index 5f5dd3d4de1..c31c363f879 100644
--- a/src/poetry/console/commands/env/remove.py
+++ b/src/poetry/console/commands/env/remove.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import argument
from cleo.helpers import option
diff --git a/src/poetry/console/commands/env/use.py b/src/poetry/console/commands/env/use.py
index 805c3b41560..2a909c34bc5 100644
--- a/src/poetry/console/commands/env/use.py
+++ b/src/poetry/console/commands/env/use.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import argument
from poetry.console.commands.command import Command
diff --git a/src/poetry/console/commands/env_command.py b/src/poetry/console/commands/env_command.py
index 938262ca29a..faff7abf59a 100644
--- a/src/poetry/console/commands/env_command.py
+++ b/src/poetry/console/commands/env_command.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.console.commands.command import Command
@@ -10,13 +12,13 @@
class EnvCommand(Command):
def __init__(self) -> None:
# Set in poetry.console.application.Application.configure_installer
- self._env: "Env" = None # type: ignore[assignment]
+ self._env: Env = None # type: ignore[assignment]
super().__init__()
@property
- def env(self) -> "Env":
+ def env(self) -> Env:
return self._env
- def set_env(self, env: "Env") -> None:
+ def set_env(self, env: Env) -> None:
self._env = env
diff --git a/src/poetry/console/commands/export.py b/src/poetry/console/commands/export.py
index c28f69384e3..c4cdb0f01ac 100644
--- a/src/poetry/console/commands/export.py
+++ b/src/poetry/console/commands/export.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import option
from poetry.console.commands.command import Command
diff --git a/src/poetry/console/commands/init.py b/src/poetry/console/commands/init.py
index ecc6a1a8a59..b2271518ed9 100644
--- a/src/poetry/console/commands/init.py
+++ b/src/poetry/console/commands/init.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import re
import sys
@@ -6,12 +8,7 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
from typing import Mapping
-from typing import Optional
-from typing import Tuple
-from typing import Union
from cleo.helpers import option
from tomlkit import inline_table
@@ -66,7 +63,7 @@ class InitCommand(Command):
def __init__(self) -> None:
super().__init__()
- self._pool: Optional["Pool"] = None
+ self._pool: Pool | None = None
def handle(self) -> int:
from pathlib import Path
@@ -197,7 +194,7 @@ def handle(self) -> int:
if self.io.is_interactive():
self.line("")
- dev_requirements: Dict[str, str] = {}
+ dev_requirements: dict[str, str] = {}
if self.option("dev-dependency"):
dev_requirements = self._format_requirements(
self._determine_requirements(self.option("dev-dependency"))
@@ -245,8 +242,8 @@ def handle(self) -> int:
return 0
def _generate_choice_list(
- self, matches: List["Package"], canonicalized_name: str
- ) -> List[str]:
+ self, matches: list[Package], canonicalized_name: str
+ ) -> list[str]:
choices = []
matches_names = [p.name for p in matches]
exact_match = canonicalized_name in matches_names
@@ -266,10 +263,10 @@ def _generate_choice_list(
def _determine_requirements(
self,
- requires: List[str],
+ requires: list[str],
allow_prereleases: bool = False,
- source: Optional[str] = None,
- ) -> List[Dict[str, Union[str, List[str]]]]:
+ source: str | None = None,
+ ) -> list[dict[str, str | list[str]]]:
if not requires:
requires = []
@@ -385,10 +382,10 @@ def _determine_requirements(
def _find_best_version_for_package(
self,
name: str,
- required_version: Optional[str] = None,
+ required_version: str | None = None,
allow_prereleases: bool = False,
- source: Optional[str] = None,
- ) -> Tuple[str, str]:
+ source: str | None = None,
+ ) -> tuple[str, str]:
from poetry.version.version_selector import VersionSelector
selector = VersionSelector(self._get_pool())
@@ -402,7 +399,7 @@ def _find_best_version_for_package(
return package.pretty_name, selector.find_recommended_require_version(package)
- def _parse_requirements(self, requirements: List[str]) -> List[Dict[str, Any]]:
+ def _parse_requirements(self, requirements: list[str]) -> list[dict[str, Any]]:
from poetry.core.pyproject.exceptions import PyProjectException
from poetry.puzzle.provider import Provider
@@ -493,7 +490,7 @@ def _parse_requirements(self, requirements: List[str]) -> List[Dict[str, Any]]:
)
pair = pair.strip()
- require: Dict[str, str] = {}
+ require: dict[str, str] = {}
if " " in pair:
name, version = pair.split(" ", 2)
extras_m = re.search(r"\[([\w\d,-_]+)\]$", name)
@@ -533,12 +530,12 @@ def _parse_requirements(self, requirements: List[str]) -> List[Dict[str, Any]]:
return result
def _format_requirements(
- self, requirements: List[Dict[str, str]]
- ) -> Mapping[str, Union[str, Mapping[str, str]]]:
+ self, requirements: list[dict[str, str]]
+ ) -> Mapping[str, str | Mapping[str, str]]:
requires = {}
for requirement in requirements:
name = requirement.pop("name")
- constraint: Union[str, "InlineTable"]
+ constraint: str | InlineTable
if "version" in requirement and len(requirement) == 1:
constraint = requirement["version"]
else:
@@ -550,7 +547,7 @@ def _format_requirements(
return requires
- def _validate_author(self, author: str, default: str) -> Optional[str]:
+ def _validate_author(self, author: str, default: str) -> str | None:
from poetry.core.packages.package import AUTHOR_REGEX
author = author or default
@@ -575,7 +572,7 @@ def _validate_license(self, license: str) -> str:
return license
- def _get_pool(self) -> "Pool":
+ def _get_pool(self) -> Pool:
from poetry.repositories import Pool
from poetry.repositories.pypi_repository import PyPiRepository
diff --git a/src/poetry/console/commands/install.py b/src/poetry/console/commands/install.py
index 2c71a687341..d99415561cd 100644
--- a/src/poetry/console/commands/install.py
+++ b/src/poetry/console/commands/install.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import option
from poetry.console.commands.installer_command import InstallerCommand
diff --git a/src/poetry/console/commands/installer_command.py b/src/poetry/console/commands/installer_command.py
index 0114b3fd1b7..5216dc2d37b 100644
--- a/src/poetry/console/commands/installer_command.py
+++ b/src/poetry/console/commands/installer_command.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.console.commands.env_command import EnvCommand
@@ -10,7 +12,7 @@
class InstallerCommand(EnvCommand):
def __init__(self) -> None:
# Set in poetry.console.application.Application.configure_installer
- self._installer: "Installer" = None # type: ignore[assignment]
+ self._installer: Installer = None # type: ignore[assignment]
super().__init__()
@@ -21,8 +23,8 @@ def reset_poetry(self) -> None:
self._installer.set_locker(self.poetry.locker)
@property
- def installer(self) -> "Installer":
+ def installer(self) -> Installer:
return self._installer
- def set_installer(self, installer: "Installer") -> None:
+ def set_installer(self, installer: Installer) -> None:
self._installer = installer
diff --git a/src/poetry/console/commands/lock.py b/src/poetry/console/commands/lock.py
index fd7510370c3..456e511e6e3 100644
--- a/src/poetry/console/commands/lock.py
+++ b/src/poetry/console/commands/lock.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import option
from poetry.console.commands.installer_command import InstallerCommand
diff --git a/src/poetry/console/commands/new.py b/src/poetry/console/commands/new.py
index 87bfe966d74..40e8cc0fcd0 100644
--- a/src/poetry/console/commands/new.py
+++ b/src/poetry/console/commands/new.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import sys
from contextlib import suppress
diff --git a/src/poetry/console/commands/plugin/add.py b/src/poetry/console/commands/plugin/add.py
index 6a9b69e2440..6fc45c28c2a 100644
--- a/src/poetry/console/commands/plugin/add.py
+++ b/src/poetry/console/commands/plugin/add.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
import os
-from typing import Dict
-from typing import List
from typing import cast
from cleo.helpers import argument
@@ -176,8 +176,8 @@ def handle(self) -> int:
)
def get_existing_packages_from_input(
- self, packages: List[str], poetry_content: Dict, target_section: str
- ) -> List[str]:
+ self, packages: list[str], poetry_content: dict, target_section: str
+ ) -> list[str]:
existing_packages = []
for name in packages:
@@ -187,7 +187,7 @@ def get_existing_packages_from_input(
return existing_packages
- def notify_about_existing_packages(self, existing_packages: List[str]) -> None:
+ def notify_about_existing_packages(self, existing_packages: list[str]) -> None:
self.line(
"The following plugins are already present in the "
"pyproject.toml file and will be skipped:\n"
diff --git a/src/poetry/console/commands/plugin/remove.py b/src/poetry/console/commands/plugin/remove.py
index cb9ada41ea3..ae8db05e795 100644
--- a/src/poetry/console/commands/plugin/remove.py
+++ b/src/poetry/console/commands/plugin/remove.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
from typing import cast
diff --git a/src/poetry/console/commands/plugin/show.py b/src/poetry/console/commands/plugin/show.py
index 1d8a8e599dc..f772f59ef72 100644
--- a/src/poetry/console/commands/plugin/show.py
+++ b/src/poetry/console/commands/plugin/show.py
@@ -1,9 +1,8 @@
+from __future__ import annotations
+
from collections import defaultdict
from typing import TYPE_CHECKING
from typing import DefaultDict
-from typing import Dict
-from typing import List
-from typing import Union
from poetry.console.commands.command import Command
@@ -26,7 +25,7 @@ def handle(self) -> int:
from poetry.utils.helpers import canonicalize_name
from poetry.utils.helpers import pluralize
- plugins: DefaultDict[str, Dict[str, Union["Package", List[str]]]] = defaultdict(
+ plugins: DefaultDict[str, dict[str, Package | list[str]]] = defaultdict(
lambda: {
"package": None,
"plugins": [],
diff --git a/src/poetry/console/commands/publish.py b/src/poetry/console/commands/publish.py
index 7daa81a0ac0..57dfba511bd 100644
--- a/src/poetry/console/commands/publish.py
+++ b/src/poetry/console/commands/publish.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from pathlib import Path
-from typing import Optional
from cleo.helpers import option
@@ -41,7 +42,7 @@ class PublishCommand(Command):
loggers = ["poetry.masonry.publishing.publisher"]
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
from poetry.publishing.publisher import Publisher
publisher = Publisher(self.poetry, self.io)
diff --git a/src/poetry/console/commands/remove.py b/src/poetry/console/commands/remove.py
index 124264a6aff..5a79c9e724d 100644
--- a/src/poetry/console/commands/remove.py
+++ b/src/poetry/console/commands/remove.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import Any
-from typing import Dict
-from typing import List
from cleo.helpers import argument
from cleo.helpers import option
@@ -113,8 +113,8 @@ def handle(self) -> int:
return status
def _remove_packages(
- self, packages: List[str], section: Dict[str, Any], group_name: str
- ) -> List[str]:
+ self, packages: list[str], section: dict[str, Any], group_name: str
+ ) -> list[str]:
removed = []
group = self.poetry.package.dependency_group(group_name)
section_keys = list(section.keys())
diff --git a/src/poetry/console/commands/run.py b/src/poetry/console/commands/run.py
index 071909d0fb0..ea878be56d0 100644
--- a/src/poetry/console/commands/run.py
+++ b/src/poetry/console/commands/run.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import Union
from cleo.helpers import argument
@@ -36,7 +36,7 @@ def handle(self) -> Any:
return 1
@property
- def _module(self) -> "Module":
+ def _module(self) -> Module:
from poetry.core.masonry.utils.module import Module
poetry = self.poetry
@@ -46,7 +46,7 @@ def _module(self) -> "Module":
return module
- def run_script(self, script: Union[str, Dict[str, str]], args: str) -> Any:
+ def run_script(self, script: str | dict[str, str], args: str) -> Any:
if isinstance(script, dict):
script = script["callable"]
diff --git a/src/poetry/console/commands/search.py b/src/poetry/console/commands/search.py
index 93858cb27d6..acb9e57addc 100644
--- a/src/poetry/console/commands/search.py
+++ b/src/poetry/console/commands/search.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import argument
from poetry.console.commands.command import Command
diff --git a/src/poetry/console/commands/self/update.py b/src/poetry/console/commands/self/update.py
index 6e39fa16f82..32ffaff1cef 100644
--- a/src/poetry/console/commands/self/update.py
+++ b/src/poetry/console/commands/self/update.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import shutil
import site
@@ -73,7 +75,7 @@ def bin_dir(self) -> Path:
return self._bin_dir
@property
- def pool(self) -> "Pool":
+ def pool(self) -> Pool:
if self._pool is not None:
return self._pool
@@ -103,7 +105,7 @@ def handle(self) -> int:
self.line("No release found for the specified version")
return 1
- def cmp(x: "Package", y: "Package") -> int:
+ def cmp(x: Package, y: Package) -> int:
if x.version == y.version:
return 0
return int(x.version < y.version or -1)
@@ -144,7 +146,7 @@ def cmp(x: "Package", y: "Package") -> int:
return 0
- def update(self, release: "Package") -> None:
+ def update(self, release: Package) -> None:
from poetry.utils.env import EnvManager
version = release.version
@@ -166,7 +168,7 @@ def update(self, release: "Package") -> None:
self._update(version)
self._make_bin()
- def _update(self, version: "Version") -> None:
+ def _update(self, version: Version) -> None:
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.project_package import ProjectPackage
diff --git a/src/poetry/console/commands/shell.py b/src/poetry/console/commands/shell.py
index 177c1792a8c..baac952acae 100644
--- a/src/poetry/console/commands/shell.py
+++ b/src/poetry/console/commands/shell.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import sys
from distutils.util import strtobool
diff --git a/src/poetry/console/commands/show.py b/src/poetry/console/commands/show.py
index e9fcefec3ce..cde50e3aff1 100644
--- a/src/poetry/console/commands/show.py
+++ b/src/poetry/console/commands/show.py
@@ -1,7 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
-from typing import Union
from cleo.helpers import argument
from cleo.helpers import option
@@ -76,7 +75,7 @@ class ShowCommand(EnvCommand):
colors = ["cyan", "yellow", "green", "magenta", "blue"]
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
from cleo.io.null_io import NullIO
from cleo.terminal import Terminal
@@ -345,7 +344,7 @@ def handle(self) -> Optional[int]:
return None
def display_package_tree(
- self, io: "IO", package: "Package", installed_repo: "Repository"
+ self, io: IO, package: Package, installed_repo: Repository
) -> None:
io.write(f"{package.pretty_name}")
description = ""
@@ -379,10 +378,10 @@ def display_package_tree(
def _display_tree(
self,
- io: "IO",
- dependency: "Dependency",
- installed_repo: "Repository",
- packages_in_tree: List[str],
+ io: IO,
+ dependency: Dependency,
+ installed_repo: Repository,
+ packages_in_tree: list[str],
previous_tree_bar: str = "├",
level: int = 1,
) -> None:
@@ -425,7 +424,7 @@ def _display_tree(
io, dependency, installed_repo, current_tree, tree_bar, level + 1
)
- def _write_tree_line(self, io: "IO", line: str) -> None:
+ def _write_tree_line(self, io: IO, line: str) -> None:
if not io.output.supports_utf8():
line = line.replace("└", "`-")
line = line.replace("├", "|-")
@@ -434,7 +433,7 @@ def _write_tree_line(self, io: "IO", line: str) -> None:
io.write_line(line)
- def init_styles(self, io: "IO") -> None:
+ def init_styles(self, io: IO) -> None:
from cleo.formatters.style import Style
for color in self.colors:
@@ -443,8 +442,8 @@ def init_styles(self, io: "IO") -> None:
io.error_output.formatter.set_style(color, style)
def find_latest_package(
- self, package: "Package", root: "ProjectPackage"
- ) -> Union["Package", bool]:
+ self, package: Package, root: ProjectPackage
+ ) -> Package | bool:
from cleo.io.null_io import NullIO
from poetry.puzzle.provider import Provider
@@ -470,7 +469,7 @@ def find_latest_package(
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
if latest.full_pretty_version == package.full_pretty_version:
@@ -486,7 +485,7 @@ def get_update_status(self, latest: "Package", package: "Package") -> str:
return "update-possible"
def get_installed_status(
- self, locked: "Package", installed_repo: "InstalledRepository"
+ self, locked: Package, installed_repo: InstalledRepository
) -> str:
for package in installed_repo.packages:
if locked.name == package.name:
diff --git a/src/poetry/console/commands/source/add.py b/src/poetry/console/commands/source/add.py
index f0135714815..ace0e16e405 100644
--- a/src/poetry/console/commands/source/add.py
+++ b/src/poetry/console/commands/source/add.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
from cleo.helpers import argument
from cleo.helpers import option
@@ -41,14 +42,14 @@ class SourceAddCommand(Command):
]
@staticmethod
- def source_to_table(source: Source) -> "Table":
- source_table: "Table" = table()
+ def source_to_table(source: Source) -> Table:
+ source_table: Table = table()
for key, value in source.to_dict().items():
source_table.add(key, value)
source_table.add(nl())
return source_table
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
from poetry.factory import Factory
from poetry.repositories import Pool
@@ -64,7 +65,7 @@ def handle(self) -> Optional[int]:
)
return 1
- new_source: Optional[Source] = Source(
+ new_source: Source | None = Source(
name=name, url=url, default=is_default, secondary=is_secondary
)
existing_sources = self.poetry.get_sources()
diff --git a/src/poetry/console/commands/source/remove.py b/src/poetry/console/commands/source/remove.py
index e09dedd6083..64c9be60057 100644
--- a/src/poetry/console/commands/source/remove.py
+++ b/src/poetry/console/commands/source/remove.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
from cleo.helpers import argument
from tomlkit import nl
@@ -28,14 +29,14 @@ class SourceRemoveCommand(Command):
]
@staticmethod
- def source_to_table(source: "Source") -> "Table":
- source_table: "Table" = table()
+ def source_to_table(source: Source) -> Table:
+ source_table: Table = table()
for key, value in source.to_dict().items():
source_table.add(key, value)
source_table.add(nl())
return source_table
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
name = self.argument("name")
sources = AoT([])
diff --git a/src/poetry/console/commands/source/show.py b/src/poetry/console/commands/source/show.py
index 23cfedfbccc..8ed4b360ec9 100644
--- a/src/poetry/console/commands/source/show.py
+++ b/src/poetry/console/commands/source/show.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from __future__ import annotations
from cleo.helpers import argument
@@ -18,7 +18,7 @@ class SourceShowCommand(Command):
),
]
- def handle(self) -> Optional[int]:
+ def handle(self) -> int | None:
sources = self.poetry.get_sources()
names = self.argument("source")
diff --git a/src/poetry/console/commands/update.py b/src/poetry/console/commands/update.py
index d2413e7109c..03c6a4ea4a4 100644
--- a/src/poetry/console/commands/update.py
+++ b/src/poetry/console/commands/update.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.helpers import argument
from cleo.helpers import option
diff --git a/src/poetry/console/commands/version.py b/src/poetry/console/commands/version.py
index 944104860c9..0ae4302ac5e 100644
--- a/src/poetry/console/commands/version.py
+++ b/src/poetry/console/commands/version.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from cleo.helpers import argument
@@ -76,7 +78,7 @@ def handle(self) -> None:
f" {self.poetry.package.pretty_version}>"
)
- def increment_version(self, version: str, rule: str) -> "Version":
+ def increment_version(self, version: str, rule: str) -> Version:
from poetry.core.semver.version import Version
try:
diff --git a/src/poetry/console/exceptions.py b/src/poetry/console/exceptions.py
index 04e2d84ffa7..f72903f757a 100644
--- a/src/poetry/console/exceptions.py
+++ b/src/poetry/console/exceptions.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.exceptions import CleoSimpleException
diff --git a/src/poetry/console/io/inputs/run_argv_input.py b/src/poetry/console/io/inputs/run_argv_input.py
index 1a0dd3c7496..964d88c2c17 100644
--- a/src/poetry/console/io/inputs/run_argv_input.py
+++ b/src/poetry/console/io/inputs/run_argv_input.py
@@ -1,7 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
-from typing import Union
from cleo.io.inputs.argv_input import ArgvInput
@@ -13,22 +12,22 @@
class RunArgvInput(ArgvInput):
def __init__(
self,
- argv: Optional[List[str]] = None,
- definition: Optional["Definition"] = None,
+ argv: list[str] | None = None,
+ definition: Definition | None = None,
) -> None:
super().__init__(argv, definition=definition)
- self._parameter_options: List[str] = []
+ self._parameter_options: list[str] = []
@property
- def first_argument(self) -> Optional[str]:
+ def first_argument(self) -> str | None:
return "run"
def add_parameter_option(self, name: str) -> None:
self._parameter_options.append(name)
def has_parameter_option(
- self, values: Union[str, List[str]], only_params: bool = False
+ self, values: str | list[str], only_params: bool = False
) -> bool:
if not isinstance(values, list):
values = [values]
diff --git a/src/poetry/console/logging/formatters/__init__.py b/src/poetry/console/logging/formatters/__init__.py
index b5cd975d82e..b26ae50c4a7 100644
--- a/src/poetry/console/logging/formatters/__init__.py
+++ b/src/poetry/console/logging/formatters/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.console.logging.formatters.builder_formatter import BuilderLogFormatter
diff --git a/src/poetry/console/logging/formatters/builder_formatter.py b/src/poetry/console/logging/formatters/builder_formatter.py
index 2728775a11e..541bb2fa27f 100644
--- a/src/poetry/console/logging/formatters/builder_formatter.py
+++ b/src/poetry/console/logging/formatters/builder_formatter.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import re
from poetry.console.logging.formatters.formatter import Formatter
diff --git a/src/poetry/console/logging/formatters/formatter.py b/src/poetry/console/logging/formatters/formatter.py
index 74d430b4812..8f2fb060696 100644
--- a/src/poetry/console/logging/formatters/formatter.py
+++ b/src/poetry/console/logging/formatters/formatter.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
@@ -6,5 +8,5 @@
class Formatter:
- def format(self, record: "logging.LogRecord") -> str:
+ def format(self, record: logging.LogRecord) -> str:
raise NotImplementedError()
diff --git a/src/poetry/console/logging/io_formatter.py b/src/poetry/console/logging/io_formatter.py
index f231ef30224..aa3630f380a 100644
--- a/src/poetry/console/logging/io_formatter.py
+++ b/src/poetry/console/logging/io_formatter.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import logging
from typing import TYPE_CHECKING
@@ -18,7 +20,7 @@ class IOFormatter(logging.Formatter):
"info": "fg=blue",
}
- def format(self, record: "LogRecord") -> str:
+ def format(self, record: LogRecord) -> str:
if not record.exc_info:
level = record.levelname.lower()
msg = record.msg
diff --git a/src/poetry/console/logging/io_handler.py b/src/poetry/console/logging/io_handler.py
index 78ccfd26a1e..213a87a3658 100644
--- a/src/poetry/console/logging/io_handler.py
+++ b/src/poetry/console/logging/io_handler.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import logging
from typing import TYPE_CHECKING
@@ -10,12 +12,12 @@
class IOHandler(logging.Handler):
- def __init__(self, io: "IO") -> None:
+ def __init__(self, io: IO) -> None:
self._io = io
super().__init__()
- def emit(self, record: "LogRecord") -> None:
+ def emit(self, record: LogRecord) -> None:
try:
msg = self.format(record)
level = record.levelname.lower()
diff --git a/src/poetry/exceptions.py b/src/poetry/exceptions.py
index 0bbaeb80a1d..65fcc609390 100644
--- a/src/poetry/exceptions.py
+++ b/src/poetry/exceptions.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+
class PoetryException(Exception):
pass
diff --git a/src/poetry/factory.py b/src/poetry/factory.py
index f6666488d73..2a0b0b6955f 100644
--- a/src/poetry/factory.py
+++ b/src/poetry/factory.py
@@ -1,8 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
-from typing import Optional
from cleo.io.null_io import NullIO
from poetry.core.factory import Factory as BaseFactory
@@ -30,8 +29,8 @@ class Factory(BaseFactory):
def create_poetry(
self,
- cwd: Optional[Path] = None,
- io: Optional["IO"] = None,
+ cwd: Path | None = None,
+ io: IO | None = None,
disable_plugins: bool = False,
) -> Poetry:
if io is None:
@@ -90,7 +89,7 @@ def get_package(cls, name: str, version: str) -> ProjectPackage:
return ProjectPackage(name, version, version)
@classmethod
- def create_config(cls, io: Optional["IO"] = None) -> Config:
+ def create_config(cls, io: IO | None = None) -> Config:
if io is None:
io = NullIO()
@@ -123,7 +122,7 @@ def create_config(cls, io: Optional["IO"] = None) -> Config:
@classmethod
def configure_sources(
- cls, poetry: Poetry, sources: List[Dict[str, str]], config: Config, io: "IO"
+ cls, poetry: Poetry, sources: list[dict[str, str]], config: Config, io: IO
) -> None:
for source in sources:
repository = cls.create_legacy_repository(source, config)
@@ -154,8 +153,8 @@ def configure_sources(
@classmethod
def create_legacy_repository(
- cls, source: Dict[str, str], auth_config: Config
- ) -> "LegacyRepository":
+ cls, source: dict[str, str], auth_config: Config
+ ) -> LegacyRepository:
from poetry.repositories.legacy_repository import LegacyRepository
from poetry.utils.helpers import get_cert
from poetry.utils.helpers import get_client_cert
diff --git a/src/poetry/inspection/info.py b/src/poetry/inspection/info.py
index 7d754c0bb6f..84f3b8fbf20 100644
--- a/src/poetry/inspection/info.py
+++ b/src/poetry/inspection/info.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import glob
import logging
import os
@@ -6,11 +8,7 @@
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
from typing import Iterator
-from typing import List
-from typing import Optional
-from typing import Union
import pkginfo
@@ -46,9 +44,7 @@
class PackageInfoError(ValueError):
- def __init__(
- self, path: Union[Path, str], *reasons: Union[BaseException, str]
- ) -> None:
+ def __init__(self, path: Path | str, *reasons: BaseException | str) -> None:
reasons = (f"Unable to determine package info for path: {path!s}",) + reasons
super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg))
@@ -56,14 +52,14 @@ def __init__(
class PackageInfo:
def __init__(
self,
- name: Optional[str] = None,
- version: Optional[str] = None,
- summary: Optional[str] = None,
- platform: Optional[str] = None,
- requires_dist: Optional[List[str]] = None,
- requires_python: Optional[str] = None,
- files: Optional[List[Dict[str, str]]] = None,
- cache_version: Optional[str] = None,
+ name: str | None = None,
+ version: str | None = None,
+ summary: str | None = None,
+ platform: str | None = None,
+ requires_dist: list[str] | None = None,
+ requires_python: str | None = None,
+ files: list[dict[str, str]] | None = None,
+ cache_version: str | None = None,
):
self.name = name
self.version = version
@@ -78,10 +74,10 @@ def __init__(
self._source_reference = None
@property
- def cache_version(self) -> Optional[str]:
+ def cache_version(self) -> str | None:
return self._cache_version
- def update(self, other: "PackageInfo") -> "PackageInfo":
+ def update(self, other: PackageInfo) -> PackageInfo:
self.name = other.name or self.name
self.version = other.version or self.version
self.summary = other.summary or self.summary
@@ -92,7 +88,7 @@ def update(self, other: "PackageInfo") -> "PackageInfo":
self._cache_version = other.cache_version or self._cache_version
return self
- def asdict(self) -> Dict[str, Optional[Union[str, List[str]]]]:
+ def asdict(self) -> dict[str, str | list[str] | None]:
"""
Helper method to convert package info into a dictionary used for caching.
"""
@@ -108,7 +104,7 @@ def asdict(self) -> Dict[str, Optional[Union[str, List[str]]]]:
}
@classmethod
- def load(cls, data: Dict[str, Optional[Union[str, List[str]]]]) -> "PackageInfo":
+ def load(cls, data: dict[str, str | list[str] | None]) -> PackageInfo:
"""
Helper method to load data from a dictionary produced by `PackageInfo.asdict()`.
@@ -125,9 +121,9 @@ def _log(cls, msg: str, level: str = "info") -> None:
def to_package(
self,
- name: Optional[str] = None,
- extras: Optional[List[str]] = None,
- root_dir: Optional[Path] = None,
+ name: str | None = None,
+ extras: list[str] | None = None,
+ root_dir: Path | None = None,
) -> Package:
"""
Create a new `poetry.core.packages.package.Package` instance using metadata from
@@ -208,8 +204,8 @@ def to_package(
@classmethod
def _from_distribution(
- cls, dist: Union[pkginfo.BDist, pkginfo.SDist, pkginfo.Wheel]
- ) -> "PackageInfo":
+ cls, dist: pkginfo.BDist | pkginfo.SDist | pkginfo.Wheel
+ ) -> PackageInfo:
"""
Helper method to parse package information from a `pkginfo.Distribution`
instance.
@@ -241,7 +237,7 @@ def _from_distribution(
return info
@classmethod
- def _from_sdist_file(cls, path: Path) -> "PackageInfo":
+ def _from_sdist_file(cls, path: Path) -> PackageInfo:
"""
Helper method to parse package information from an sdist file. We attempt to
first inspect the file using `pkginfo.SDist`. If this does not provide us with
@@ -306,7 +302,7 @@ def has_setup_files(path: Path) -> bool:
return any((path / f).exists() for f in SetupReader.FILES)
@classmethod
- def from_setup_files(cls, path: Path) -> "PackageInfo":
+ def from_setup_files(cls, path: Path) -> PackageInfo:
"""
Mechanism to parse package information from a `setup.[py|cfg]` file. This uses
the implementation at `poetry.utils.setup_reader.SetupReader` in order to parse
@@ -377,7 +373,7 @@ def _find_dist_info(path: Path) -> Iterator[Path]:
yield Path(d)
@classmethod
- def from_metadata(cls, path: Path) -> Optional["PackageInfo"]:
+ def from_metadata(cls, path: Path) -> PackageInfo | None:
"""
Helper method to parse package information from an unpacked metadata directory.
@@ -412,7 +408,7 @@ def from_metadata(cls, path: Path) -> Optional["PackageInfo"]:
return None
@classmethod
- def from_package(cls, package: Package) -> "PackageInfo":
+ def from_package(cls, package: Package) -> PackageInfo:
"""
Helper method to inspect a `Package` object, in order to generate package info.
@@ -435,7 +431,7 @@ def from_package(cls, package: Package) -> "PackageInfo":
)
@staticmethod
- def _get_poetry_package(path: Path) -> Optional["ProjectPackage"]:
+ def _get_poetry_package(path: Path) -> ProjectPackage | None:
# Note: we ignore any setup.py file at this step
# TODO: add support for handling non-poetry PEP-517 builds
if PyProjectTOML(path.joinpath("pyproject.toml")).is_poetry_project():
@@ -443,7 +439,7 @@ def _get_poetry_package(path: Path) -> Optional["ProjectPackage"]:
return None
@classmethod
- def _pep517_metadata(cls, path: Path) -> "PackageInfo":
+ def _pep517_metadata(cls, path: Path) -> PackageInfo:
"""
Helper method to use PEP-517 library to build and read package metadata.
@@ -513,7 +509,7 @@ def _pep517_metadata(cls, path: Path) -> "PackageInfo":
raise PackageInfoError(path, "Exhausted all core metadata sources.")
@classmethod
- def from_directory(cls, path: Path, disable_build: bool = False) -> "PackageInfo":
+ def from_directory(cls, path: Path, disable_build: bool = False) -> PackageInfo:
"""
Generate package information from a package source directory. If `disable_build`
is not `True` and introspection of all available metadata fails, the package is
@@ -548,7 +544,7 @@ def from_directory(cls, path: Path, disable_build: bool = False) -> "PackageInfo
return info
@classmethod
- def from_sdist(cls, path: Path) -> "PackageInfo":
+ def from_sdist(cls, path: Path) -> PackageInfo:
"""
Gather package information from an sdist file, packed or unpacked.
@@ -562,7 +558,7 @@ def from_sdist(cls, path: Path) -> "PackageInfo":
return cls.from_directory(path=path)
@classmethod
- def from_wheel(cls, path: Path) -> "PackageInfo":
+ def from_wheel(cls, path: Path) -> PackageInfo:
"""
Gather package information from a wheel.
@@ -574,7 +570,7 @@ def from_wheel(cls, path: Path) -> "PackageInfo":
return PackageInfo()
@classmethod
- def from_bdist(cls, path: Path) -> "PackageInfo":
+ def from_bdist(cls, path: Path) -> PackageInfo:
"""
Gather package information from a bdist (wheel etc.).
@@ -592,7 +588,7 @@ def from_bdist(cls, path: Path) -> "PackageInfo":
raise PackageInfoError(path, e)
@classmethod
- def from_path(cls, path: Path) -> "PackageInfo":
+ def from_path(cls, path: Path) -> PackageInfo:
"""
Gather package information from a given path (bdist, sdist, directory).
diff --git a/src/poetry/installation/__init__.py b/src/poetry/installation/__init__.py
index 7bad39a5364..b7bc1c52e31 100644
--- a/src/poetry/installation/__init__.py
+++ b/src/poetry/installation/__init__.py
@@ -1 +1,3 @@
+from __future__ import annotations
+
from poetry.installation.installer import Installer
diff --git a/src/poetry/installation/base_installer.py b/src/poetry/installation/base_installer.py
index ecb6dadf3df..8e1d3197618 100644
--- a/src/poetry/installation/base_installer.py
+++ b/src/poetry/installation/base_installer.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
@@ -6,11 +8,11 @@
class BaseInstaller:
- def install(self, package: "Package") -> None:
+ def install(self, package: Package) -> None:
raise NotImplementedError
- def update(self, source: "Package", target: "Package") -> None:
+ def update(self, source: Package, target: Package) -> None:
raise NotImplementedError
- def remove(self, package: "Package") -> None:
+ def remove(self, package: Package) -> None:
raise NotImplementedError
diff --git a/src/poetry/installation/chef.py b/src/poetry/installation/chef.py
index 40d6f767625..0cf7b54e3b5 100644
--- a/src/poetry/installation/chef.py
+++ b/src/poetry/installation/chef.py
@@ -1,10 +1,10 @@
+from __future__ import annotations
+
import hashlib
import json
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
from poetry.core.packages.utils.link import Link
@@ -19,7 +19,7 @@
class Chef:
- def __init__(self, config: "Config", env: "Env") -> None:
+ def __init__(self, config: Config, env: Env) -> None:
self._config = config
self._env = env
self._cache_dir = (
@@ -41,7 +41,7 @@ def should_prepare(self, archive: Path) -> bool:
def is_wheel(self, archive: Path) -> bool:
return archive.suffix == ".whl"
- def get_cached_archive_for_link(self, link: Link) -> Optional[Link]:
+ def get_cached_archive_for_link(self, link: Link) -> Link | None:
# If the archive is already a wheel, there is no need to cache it.
if link.is_wheel:
return link
@@ -74,7 +74,7 @@ def get_cached_archive_for_link(self, link: Link) -> Optional[Link]:
return min(candidates)[1]
- def get_cached_archives_for_link(self, link: Link) -> List[Link]:
+ def get_cached_archives_for_link(self, link: Link) -> list[Link]:
cache_dir = self.get_cache_directory_for_link(link)
archive_types = ["whl", "tar.gz", "tar.bz2", "bz2", "zip"]
diff --git a/src/poetry/installation/chooser.py b/src/poetry/installation/chooser.py
index 73e6bd5bed0..424aaefe7bb 100644
--- a/src/poetry/installation/chooser.py
+++ b/src/poetry/installation/chooser.py
@@ -1,9 +1,8 @@
+from __future__ import annotations
+
import re
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
-from typing import Tuple
from packaging.tags import Tag
@@ -40,12 +39,12 @@ def __init__(self, filename: str) -> None:
Tag(x, y, z) for x in self.pyversions for y in self.abis for z in self.plats
}
- def get_minimum_supported_index(self, tags: List[Tag]) -> Optional[int]:
+ def get_minimum_supported_index(self, tags: list[Tag]) -> int | None:
indexes = [tags.index(t) for t in self.tags if t in tags]
return min(indexes) if indexes else None
- def is_supported_by_environment(self, env: "Env") -> bool:
+ def is_supported_by_environment(self, env: Env) -> bool:
return bool(set(env.supported_tags).intersection(self.tags))
@@ -54,11 +53,11 @@ class Chooser:
A Chooser chooses an appropriate release archive for packages.
"""
- def __init__(self, pool: "Pool", env: "Env") -> None:
+ def __init__(self, pool: Pool, env: Env) -> None:
self._pool = pool
self._env = env
- def choose_for(self, package: "Package") -> "Link":
+ def choose_for(self, package: Package) -> Link:
"""
Return the url of the selected archive for a given package.
"""
@@ -84,7 +83,7 @@ def choose_for(self, package: "Package") -> "Link":
return chosen
- def _get_links(self, package: "Package") -> List["Link"]:
+ def _get_links(self, package: Package) -> list[Link]:
if package.source_type:
repository = self._pool.repository(package.source_reference)
@@ -118,7 +117,7 @@ def _get_links(self, package: "Package") -> List["Link"]:
return selected_links
- def _sort_key(self, package: "Package", link: "Link") -> Tuple:
+ def _sort_key(self, package: Package, link: Link) -> tuple:
"""
Function to pass as the `key` argument to a call to sorted() to sort
InstallationCandidates by preference.
@@ -176,9 +175,7 @@ def _sort_key(self, package: "Package", link: "Link") -> Tuple:
pri,
)
- def _is_link_hash_allowed_for_package(
- self, link: "Link", package: "Package"
- ) -> bool:
+ def _is_link_hash_allowed_for_package(self, link: Link, package: Package) -> bool:
if not link.hash:
return True
diff --git a/src/poetry/installation/executor.py b/src/poetry/installation/executor.py
index b9dcd8e92f6..b45a518d164 100644
--- a/src/poetry/installation/executor.py
+++ b/src/poetry/installation/executor.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import csv
import itertools
import json
@@ -10,10 +12,6 @@
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Union
from cleo.io.null_io import NullIO
from poetry.core.packages.file_dependency import FileDependency
@@ -49,10 +47,10 @@
class Executor:
def __init__(
self,
- env: "Env",
- pool: "Pool",
- config: "Config",
- io: "IO",
+ env: Env,
+ pool: Pool,
+ config: Config,
+ io: IO,
parallel: bool = None,
) -> None:
self._env = env
@@ -82,7 +80,7 @@ def __init__(
self._sections = {}
self._lock = threading.Lock()
self._shutdown = False
- self._hashes: Dict[str, str] = {}
+ self._hashes: dict[str, str] = {}
@property
def installations_count(self) -> int:
@@ -99,23 +97,23 @@ def removals_count(self) -> int:
def supports_fancy_output(self) -> bool:
return self._io.output.is_decorated() and not self._dry_run
- def disable(self) -> "Executor":
+ def disable(self) -> Executor:
self._enabled = False
return self
- def dry_run(self, dry_run: bool = True) -> "Executor":
+ def dry_run(self, dry_run: bool = True) -> Executor:
self._dry_run = dry_run
return self
- def verbose(self, verbose: bool = True) -> "Executor":
+ def verbose(self, verbose: bool = True) -> Executor:
self._verbose = verbose
return self
def pip_install(
- self, req: Union[Path, Link], upgrade: bool = False, editable: bool = False
+ self, req: Path | Link, upgrade: bool = False, editable: bool = False
) -> int:
func = pip_install
if editable:
@@ -134,7 +132,7 @@ def pip_install(
return 0
- def execute(self, operations: List["OperationTypes"]) -> int:
+ def execute(self, operations: list[OperationTypes]) -> int:
self._total_operations = len(operations)
for job_type in self._executed:
self._executed[job_type] = 0
@@ -188,7 +186,7 @@ def execute(self, operations: List["OperationTypes"]) -> int:
return 1 if self._shutdown else 0
@staticmethod
- def _get_max_workers(desired_max_workers: Optional[int] = None) -> int:
+ def _get_max_workers(desired_max_workers: int | None = None) -> int:
# This should be directly handled by ThreadPoolExecutor
# however, on some systems the number of CPUs cannot be determined
# (it raises a NotImplementedError), so, in this case, we assume
@@ -202,7 +200,7 @@ def _get_max_workers(desired_max_workers: Optional[int] = None) -> int:
return default_max_workers
return min(default_max_workers, desired_max_workers)
- def _write(self, operation: "OperationTypes", line: str) -> None:
+ def _write(self, operation: OperationTypes, line: str) -> None:
if not self.supports_fancy_output() or not self._should_write_operation(
operation
):
@@ -220,7 +218,7 @@ def _write(self, operation: "OperationTypes", line: str) -> None:
section.clear()
section.write(line)
- def _execute_operation(self, operation: "OperationTypes") -> None:
+ def _execute_operation(self, operation: OperationTypes) -> None:
try:
op_message = self.get_operation_message(operation)
if self.supports_fancy_output():
@@ -297,7 +295,7 @@ def _execute_operation(self, operation: "OperationTypes") -> None:
with self._lock:
self._shutdown = True
- def _do_execute_operation(self, operation: "OperationTypes") -> int:
+ def _do_execute_operation(self, operation: OperationTypes) -> int:
method = operation.job_type
operation_message = self.get_operation_message(operation)
@@ -334,7 +332,7 @@ def _do_execute_operation(self, operation: "OperationTypes") -> int:
return result
def _increment_operations_count(
- self, operation: "OperationTypes", executed: bool
+ self, operation: OperationTypes, executed: bool
) -> None:
with self._lock:
if executed:
@@ -360,7 +358,7 @@ def run_pip(self, *args: Any, **kwargs: Any) -> int:
def get_operation_message(
self,
- operation: "OperationTypes",
+ operation: OperationTypes,
done: bool = False,
error: bool = False,
warning: bool = False,
@@ -408,7 +406,7 @@ def get_operation_message(
)
return ""
- def _display_summary(self, operations: List["OperationTypes"]) -> None:
+ def _display_summary(self, operations: list[OperationTypes]) -> None:
installs = 0
updates = 0
uninstalls = 0
@@ -441,28 +439,28 @@ def _display_summary(self, operations: List["OperationTypes"]) -> None:
self._io.write_line("")
self._io.write_line("")
- def _execute_install(self, operation: Union["Install", "Update"]) -> int:
+ def _execute_install(self, operation: Install | Update) -> int:
status_code = self._install(operation)
self._save_url_reference(operation)
return status_code
- def _execute_update(self, operation: Union["Install", "Update"]) -> int:
+ def _execute_update(self, operation: Install | Update) -> int:
status_code = self._update(operation)
self._save_url_reference(operation)
return status_code
- def _execute_uninstall(self, operation: "Uninstall") -> int:
+ def _execute_uninstall(self, operation: Uninstall) -> int:
op_msg = self.get_operation_message(operation)
message = f" •> {op_msg}: Removing..."
self._write(operation, message)
return self._remove(operation)
- def _install(self, operation: Union["Install", "Update"]) -> int:
+ def _install(self, operation: Install | Update) -> int:
package = operation.package
if package.source_type == "directory":
return self._install_directory(operation)
@@ -485,10 +483,10 @@ def _install(self, operation: Union["Install", "Update"]) -> int:
self._write(operation, message)
return self.pip_install(archive, upgrade=operation.job_type == "update")
- def _update(self, operation: Union["Install", "Update"]) -> int:
+ def _update(self, operation: Install | Update) -> int:
return self._install(operation)
- def _remove(self, operation: "Uninstall") -> int:
+ def _remove(self, operation: Uninstall) -> int:
package = operation.package
# If we have a VCS package, remove its source directory
@@ -505,7 +503,7 @@ def _remove(self, operation: "Uninstall") -> int:
raise
- def _prepare_file(self, operation: Union["Install", "Update"]) -> Path:
+ def _prepare_file(self, operation: Install | Update) -> Path:
package = operation.package
operation_message = self.get_operation_message(operation)
@@ -523,7 +521,7 @@ def _prepare_file(self, operation: Union["Install", "Update"]) -> Path:
return archive
- def _install_directory(self, operation: Union["Install", "Update"]) -> int:
+ def _install_directory(self, operation: Install | Update) -> int:
from poetry.factory import Factory
package = operation.package
@@ -582,7 +580,7 @@ def _install_directory(self, operation: Union["Install", "Update"]) -> int:
return self.pip_install(req, upgrade=True)
- def _install_git(self, operation: Union["Install", "Update"]) -> int:
+ def _install_git(self, operation: Install | Update) -> int:
from poetry.core.vcs import Git
package = operation.package
@@ -618,12 +616,12 @@ def _install_git(self, operation: Union["Install", "Update"]) -> int:
return status_code
- def _download(self, operation: Union["Install", "Update"]) -> Link:
+ def _download(self, operation: Install | Update) -> Link:
link = self._chooser.choose_for(operation.package)
return self._download_link(operation, link)
- def _download_link(self, operation: Union["Install", "Update"], link: Link) -> Link:
+ def _download_link(self, operation: Install | Update, link: Link) -> Link:
package = operation.package
archive = self._chef.get_cached_archive_for_link(link)
@@ -654,7 +652,7 @@ def _download_link(self, operation: Union["Install", "Update"], link: Link) -> L
return archive
@staticmethod
- def _validate_archive_hash(archive: Union[Path, Link], package: "Package") -> str:
+ def _validate_archive_hash(archive: Path | Link, package: Package) -> str:
archive_path = (
url_to_path(archive.url) if isinstance(archive, Link) else archive
)
@@ -673,9 +671,7 @@ def _validate_archive_hash(archive: Union[Path, Link], package: "Package") -> st
return archive_hash
- def _download_archive(
- self, operation: Union["Install", "Update"], link: Link
- ) -> Path:
+ def _download_archive(self, operation: Install | Update, link: Link) -> Path:
response = self._authenticator.request(
"get", link.url, stream=True, io=self._sections.get(id(operation), self._io)
)
@@ -722,10 +718,10 @@ def _download_archive(
return archive
- def _should_write_operation(self, operation: "Operation") -> bool:
+ def _should_write_operation(self, operation: Operation) -> bool:
return not operation.skipped or self._dry_run or self._verbose
- def _save_url_reference(self, operation: "OperationTypes") -> None:
+ def _save_url_reference(self, operation: OperationTypes) -> None:
"""
Create and store a PEP-610 `direct_url.json` file, if needed.
"""
@@ -787,8 +783,8 @@ def _save_url_reference(self, operation: "OperationTypes") -> None:
)
def _create_git_url_reference(
- self, package: "Package"
- ) -> Dict[str, Union[str, Dict[str, str]]]:
+ self, package: Package
+ ) -> dict[str, str | dict[str, str]]:
reference = {
"url": package.source_url,
"vcs_info": {
@@ -801,8 +797,8 @@ def _create_git_url_reference(
return reference
def _create_url_url_reference(
- self, package: "Package"
- ) -> Dict[str, Union[str, Dict[str, str]]]:
+ self, package: Package
+ ) -> dict[str, str | dict[str, str]]:
archive_info = {}
if package.name in self._hashes:
@@ -813,8 +809,8 @@ def _create_url_url_reference(
return reference
def _create_file_url_reference(
- self, package: "Package"
- ) -> Dict[str, Union[str, Dict[str, str]]]:
+ self, package: Package
+ ) -> dict[str, str | dict[str, str]]:
archive_info = {}
if package.name in self._hashes:
@@ -828,8 +824,8 @@ def _create_file_url_reference(
return reference
def _create_directory_url_reference(
- self, package: "Package"
- ) -> Dict[str, Union[str, Dict[str, str]]]:
+ self, package: Package
+ ) -> dict[str, str | dict[str, str]]:
dir_info = {}
if package.develop:
diff --git a/src/poetry/installation/installer.py b/src/poetry/installation/installer.py
index 2b03db67b20..d09cd925e87 100644
--- a/src/poetry/installation/installer.py
+++ b/src/poetry/installation/installer.py
@@ -1,9 +1,8 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from typing import Iterable
-from typing import List
-from typing import Optional
from typing import Sequence
-from typing import Union
from cleo.io.null_io import NullIO
@@ -35,14 +34,14 @@
class Installer:
def __init__(
self,
- io: "IO",
- env: "Env",
- package: "ProjectPackage",
- locker: "Locker",
+ io: IO,
+ env: Env,
+ package: ProjectPackage,
+ locker: Locker,
pool: Pool,
- config: "Config",
- installed: Union[Repository, None] = None,
- executor: Optional[Executor] = None,
+ config: Config,
+ installed: Repository | None = None,
+ executor: Executor | None = None,
):
self._io = io
self._env = env
@@ -83,15 +82,15 @@ def executor(self) -> Executor:
return self._executor
@property
- def installer(self) -> "BaseInstaller":
+ def installer(self) -> BaseInstaller:
return self._installer
- def set_package(self, package: "ProjectPackage") -> "Installer":
+ def set_package(self, package: ProjectPackage) -> Installer:
self._package = package
return self
- def set_locker(self, locker: "Locker") -> "Installer":
+ def set_locker(self, locker: Locker) -> Installer:
self._locker = locker
return self
@@ -114,7 +113,7 @@ def run(self) -> int:
return self._do_install(local_repo)
- def dry_run(self, dry_run: bool = True) -> "Installer":
+ def dry_run(self, dry_run: bool = True) -> Installer:
self._dry_run = dry_run
self._executor.dry_run(dry_run)
@@ -125,12 +124,12 @@ def is_dry_run(self) -> bool:
def requires_synchronization(
self, requires_synchronization: bool = True
- ) -> "Installer":
+ ) -> Installer:
self._requires_synchronization = requires_synchronization
return self
- def verbose(self, verbose: bool = True) -> "Installer":
+ def verbose(self, verbose: bool = True) -> Installer:
self._verbose = verbose
self._executor.verbose(verbose)
@@ -139,27 +138,27 @@ def verbose(self, verbose: bool = True) -> "Installer":
def is_verbose(self) -> bool:
return self._verbose
- def without_groups(self, groups: List[str]) -> "Installer":
+ def without_groups(self, groups: list[str]) -> Installer:
self._without_groups = groups
return self
- def with_groups(self, groups: List[str]) -> "Installer":
+ def with_groups(self, groups: list[str]) -> Installer:
self._with_groups = groups
return self
- def only_groups(self, groups: List[str]) -> "Installer":
+ def only_groups(self, groups: list[str]) -> Installer:
self._only_groups = groups
return self
- def update(self, update: bool = True) -> "Installer":
+ def update(self, update: bool = True) -> Installer:
self._update = update
return self
- def lock(self, update: bool = True) -> "Installer":
+ def lock(self, update: bool = True) -> Installer:
"""
Prepare the installer for locking only.
"""
@@ -172,7 +171,7 @@ def lock(self, update: bool = True) -> "Installer":
def is_updating(self) -> bool:
return self._update
- def execute_operations(self, execute: bool = True) -> "Installer":
+ def execute_operations(self, execute: bool = True) -> Installer:
self._execute_operations = execute
if not execute:
@@ -180,17 +179,17 @@ def execute_operations(self, execute: bool = True) -> "Installer":
return self
- def whitelist(self, packages: Iterable[str]) -> "Installer":
+ def whitelist(self, packages: Iterable[str]) -> Installer:
self._whitelist = [canonicalize_name(p) for p in packages]
return self
- def extras(self, extras: list) -> "Installer":
+ def extras(self, extras: list) -> Installer:
self._extras = extras
return self
- def use_executor(self, use_executor: bool = True) -> "Installer":
+ def use_executor(self, use_executor: bool = True) -> Installer:
self._use_executor = use_executor
return self
@@ -362,7 +361,7 @@ def _write_lock_file(self, repo: Repository, force: bool = True) -> None:
self._io.write_line("")
self._io.write_line("Writing lock file>")
- def _execute(self, operations: List["OperationTypes"]) -> int:
+ def _execute(self, operations: list[OperationTypes]) -> int:
if self._use_executor:
return self._executor.execute(operations)
@@ -400,7 +399,7 @@ def _execute(self, operations: List["OperationTypes"]) -> int:
return 0
- def _execute_operation(self, operation: "Operation") -> None:
+ def _execute_operation(self, operation: Operation) -> None:
"""
Execute a given operation.
"""
@@ -478,7 +477,7 @@ def _execute_uninstall(self, operation: Uninstall) -> None:
self._installer.remove(operation.package)
def _populate_local_repo(
- self, local_repo: Repository, ops: Sequence["Operation"]
+ self, local_repo: Repository, ops: Sequence[Operation]
) -> None:
for op in ops:
if isinstance(op, Uninstall):
@@ -493,7 +492,7 @@ def _populate_local_repo(
def _get_operations_from_lock(
self, locked_repository: Repository
- ) -> Sequence["Operation"]:
+ ) -> Sequence[Operation]:
installed_repo = self._installed_repository
ops = []
@@ -522,7 +521,7 @@ def _get_operations_from_lock(
return ops
- def _filter_operations(self, ops: Sequence["Operation"], repo: Repository) -> None:
+ def _filter_operations(self, ops: Sequence[Operation], repo: Repository) -> None:
extra_packages = self._get_extra_packages(repo)
for op in ops:
if isinstance(op, Update):
@@ -551,7 +550,7 @@ def _filter_operations(self, ops: Sequence["Operation"], repo: Repository) -> No
if package.optional and package.name not in extra_packages:
op.skip("Not required")
- def _get_extra_packages(self, repo: Repository) -> List[str]:
+ def _get_extra_packages(self, repo: Repository) -> list[str]:
"""
Returns all package names required by extras.
@@ -564,7 +563,7 @@ def _get_extra_packages(self, repo: Repository) -> List[str]:
return list(get_extra_package_names(repo.packages, extras, self._extras))
- def _get_installer(self) -> "BaseInstaller":
+ def _get_installer(self) -> BaseInstaller:
return PipInstaller(self._env, self._io, self._pool)
def _get_installed(self) -> InstalledRepository:
diff --git a/src/poetry/installation/noop_installer.py b/src/poetry/installation/noop_installer.py
index bbe389d2b07..84416cf4207 100644
--- a/src/poetry/installation/noop_installer.py
+++ b/src/poetry/installation/noop_installer.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
from poetry.installation.base_installer import BaseInstaller
@@ -10,27 +11,27 @@
class NoopInstaller(BaseInstaller):
def __init__(self) -> None:
- self._installs: List["Package"] = []
- self._updates: List["Package"] = []
- self._removals: List["Package"] = []
+ self._installs: list[Package] = []
+ self._updates: list[Package] = []
+ self._removals: list[Package] = []
@property
- def installs(self) -> List["Package"]:
+ def installs(self) -> list[Package]:
return self._installs
@property
- def updates(self) -> List["Package"]:
+ def updates(self) -> list[Package]:
return self._updates
@property
- def removals(self) -> List["Package"]:
+ def removals(self) -> list[Package]:
return self._removals
- def install(self, package: "Package") -> None:
+ def install(self, package: Package) -> None:
self._installs.append(package)
- def update(self, source: "Package", target: "Package") -> None:
+ def update(self, source: Package, target: Package) -> None:
self._updates.append((source, target))
- def remove(self, package: "Package") -> None:
+ def remove(self, package: Package) -> None:
self._removals.append(package)
diff --git a/src/poetry/installation/operations/__init__.py b/src/poetry/installation/operations/__init__.py
index e3996303ed4..d3c2db5cced 100644
--- a/src/poetry/installation/operations/__init__.py
+++ b/src/poetry/installation/operations/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import Union
from poetry.installation.operations.install import Install
diff --git a/src/poetry/installation/operations/install.py b/src/poetry/installation/operations/install.py
index 95014d10b96..3abb0fd5b19 100644
--- a/src/poetry/installation/operations/install.py
+++ b/src/poetry/installation/operations/install.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
from poetry.installation.operations.operation import Operation
@@ -10,14 +11,14 @@
class Install(Operation):
def __init__(
- self, package: "Package", reason: Optional[str] = None, priority: int = 0
+ self, package: Package, reason: str | None = None, priority: int = 0
) -> None:
super().__init__(reason, priority=priority)
self._package = package
@property
- def package(self) -> "Package":
+ def package(self) -> Package:
return self._package
@property
diff --git a/src/poetry/installation/operations/operation.py b/src/poetry/installation/operations/operation.py
index 2dfdb1712f9..99c12c39632 100644
--- a/src/poetry/installation/operations/operation.py
+++ b/src/poetry/installation/operations/operation.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
from typing import TypeVar
-from typing import Union
if TYPE_CHECKING:
@@ -11,13 +11,11 @@
class Operation:
- def __init__(
- self, reason: Optional[str] = None, priority: Union[int, float] = 0
- ) -> None:
+ def __init__(self, reason: str | None = None, priority: int | float = 0) -> None:
self._reason = reason
self._skipped = False
- self._skip_reason: Optional[str] = None
+ self._skip_reason: str | None = None
self._priority = priority
@property
@@ -25,7 +23,7 @@ def job_type(self) -> str:
raise NotImplementedError
@property
- def reason(self) -> Optional[str]:
+ def reason(self) -> str | None:
return self._reason
@property
@@ -33,18 +31,18 @@ def skipped(self) -> bool:
return self._skipped
@property
- def skip_reason(self) -> Optional[str]:
+ def skip_reason(self) -> str | None:
return self._skip_reason
@property
- def priority(self) -> Union[float, int]:
+ def priority(self) -> float | int:
return self._priority
@property
- def package(self) -> "Package":
+ def package(self) -> Package:
raise NotImplementedError()
- def format_version(self, package: "Package") -> str:
+ def format_version(self, package: Package) -> str:
return package.full_pretty_version
def skip(self: T, reason: str) -> T:
diff --git a/src/poetry/installation/operations/uninstall.py b/src/poetry/installation/operations/uninstall.py
index ef8464a30af..9b4a4981cb8 100644
--- a/src/poetry/installation/operations/uninstall.py
+++ b/src/poetry/installation/operations/uninstall.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
-from typing import Union
from poetry.installation.operations.operation import Operation
@@ -12,16 +12,16 @@
class Uninstall(Operation):
def __init__(
self,
- package: "Package",
- reason: Optional[str] = None,
- priority: Union[float, int] = float("inf"),
+ package: Package,
+ reason: str | None = None,
+ priority: float | int = float("inf"),
) -> None:
super().__init__(reason, priority=priority)
self._package = package
@property
- def package(self) -> "Package":
+ def package(self) -> Package:
return self._package
@property
diff --git a/src/poetry/installation/operations/update.py b/src/poetry/installation/operations/update.py
index 68ff1b66126..e67cc869b37 100644
--- a/src/poetry/installation/operations/update.py
+++ b/src/poetry/installation/operations/update.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
from poetry.installation.operations.operation import Operation
@@ -11,9 +12,9 @@
class Update(Operation):
def __init__(
self,
- initial: "Package",
- target: "Package",
- reason: Optional[str] = None,
+ initial: Package,
+ target: Package,
+ reason: str | None = None,
priority: int = 0,
) -> None:
self._initial_package = initial
@@ -22,15 +23,15 @@ def __init__(
super().__init__(reason, priority=priority)
@property
- def initial_package(self) -> "Package":
+ def initial_package(self) -> Package:
return self._initial_package
@property
- def target_package(self) -> "Package":
+ def target_package(self) -> Package:
return self._target_package
@property
- def package(self) -> "Package":
+ def package(self) -> Package:
return self._target_package
@property
diff --git a/src/poetry/installation/pip_installer.py b/src/poetry/installation/pip_installer.py
index e05fa0cfc6f..60f71a2b76e 100644
--- a/src/poetry/installation/pip_installer.py
+++ b/src/poetry/installation/pip_installer.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import tempfile
import urllib.parse
@@ -6,7 +8,6 @@
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
from typing import Any
-from typing import Union
from poetry.core.pyproject.toml import PyProjectTOML
@@ -26,12 +27,12 @@
class PipInstaller(BaseInstaller):
- def __init__(self, env: "Env", io: "IO", pool: "Pool") -> None:
+ def __init__(self, env: Env, io: IO, pool: Pool) -> None:
self._env = env
self._io = io
self._pool = pool
- def install(self, package: "Package", update: bool = False) -> None:
+ def install(self, package: Package, update: bool = False) -> None:
if package.source_type == "directory":
self.install_directory(package)
@@ -101,7 +102,7 @@ def install(self, package: "Package", update: bool = False) -> None:
self.run(*args)
- def update(self, package: "Package", target: "Package") -> None:
+ def update(self, package: Package, target: Package) -> None:
if package.source_type != target.source_type:
# If the source type has changed, we remove the current
# package to avoid perpetual updates in some cases
@@ -109,7 +110,7 @@ def update(self, package: "Package", target: "Package") -> None:
self.install(target, update=True)
- def remove(self, package: "Package") -> None:
+ def remove(self, package: Package) -> None:
try:
self.run("uninstall", package.name, "-y")
except CalledProcessError as e:
@@ -133,7 +134,7 @@ def remove(self, package: "Package") -> None:
def run(self, *args: Any, **kwargs: Any) -> str:
return self._env.run_pip(*args, **kwargs)
- def requirement(self, package: "Package", formatted: bool = False) -> str:
+ def requirement(self, package: Package, formatted: bool = False) -> str:
if formatted and not package.source_type:
req = f"{package.name}=={package.version}"
for f in package.files:
@@ -175,7 +176,7 @@ def requirement(self, package: "Package", formatted: bool = False) -> str:
return f"{package.name}=={package.version}"
- def create_temporary_requirement(self, package: "Package") -> str:
+ def create_temporary_requirement(self, package: Package) -> str:
fd, name = tempfile.mkstemp("reqs.txt", f"{package.name}-{package.version}")
try:
@@ -185,7 +186,7 @@ def create_temporary_requirement(self, package: "Package") -> str:
return name
- def install_directory(self, package: "Package") -> Union[str, int]:
+ def install_directory(self, package: Package) -> str | int:
from cleo.io.null_io import NullIO
from poetry.factory import Factory
@@ -241,7 +242,7 @@ def install_directory(self, package: "Package") -> Union[str, int]:
return pip_editable_install(directory=req, environment=self._env)
return pip_install(path=req, environment=self._env, deps=False, upgrade=True)
- def install_git(self, package: "Package") -> None:
+ def install_git(self, package: Package) -> None:
from poetry.core.packages.package import Package
from poetry.core.vcs.git import Git
diff --git a/src/poetry/json/__init__.py b/src/poetry/json/__init__.py
index 0515f6b311b..af8d3d6175d 100644
--- a/src/poetry/json/__init__.py
+++ b/src/poetry/json/__init__.py
@@ -1,8 +1,8 @@
+from __future__ import annotations
+
import json
import os
-from typing import List
-
import jsonschema
@@ -14,7 +14,7 @@ class ValidationError(ValueError):
pass
-def validate_object(obj: dict, schema_name: str) -> List[str]:
+def validate_object(obj: dict, schema_name: str) -> list[str]:
schema = os.path.join(SCHEMA_DIR, f"{schema_name}.json")
if not os.path.exists(schema):
diff --git a/src/poetry/layouts/__init__.py b/src/poetry/layouts/__init__.py
index ffa189cb57b..033b16a64fc 100644
--- a/src/poetry/layouts/__init__.py
+++ b/src/poetry/layouts/__init__.py
@@ -1,4 +1,4 @@
-from typing import Type
+from __future__ import annotations
from poetry.layouts.layout import Layout
from poetry.layouts.src import SrcLayout
@@ -7,7 +7,7 @@
_LAYOUTS = {"src": SrcLayout, "standard": Layout}
-def layout(name: str) -> Type[Layout]:
+def layout(name: str) -> type[Layout]:
if name not in _LAYOUTS:
raise ValueError("Invalid layout")
diff --git a/src/poetry/layouts/layout.py b/src/poetry/layouts/layout.py
index 9e036005a63..349dba4864f 100644
--- a/src/poetry/layouts/layout.py
+++ b/src/poetry/layouts/layout.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import Optional
from tomlkit import dumps
from tomlkit import inline_table
@@ -32,8 +32,8 @@
[tool.poetry.group.dev.dependencies]
"""
-BUILD_SYSTEM_MIN_VERSION: Optional[str] = None
-BUILD_SYSTEM_MAX_VERSION: Optional[str] = None
+BUILD_SYSTEM_MIN_VERSION: str | None = None
+BUILD_SYSTEM_MAX_VERSION: str | None = None
class Layout:
@@ -45,11 +45,11 @@ def __init__(
version: str = "0.1.0",
description: str = "",
readme_format: str = "md",
- author: Optional[str] = None,
- license: Optional[str] = None,
+ author: str | None = None,
+ license: str | None = None,
python: str = "*",
- dependencies: Optional[Dict[str, str]] = None,
- dev_dependencies: Optional[Dict[str, str]] = None,
+ dependencies: dict[str, str] | None = None,
+ dev_dependencies: dict[str, str] | None = None,
):
self._project = canonicalize_name(project).replace(".", "-")
self._package_path_relative = Path(
@@ -85,7 +85,7 @@ def basedir(self) -> Path:
def package_path(self) -> Path:
return self.basedir / self._package_path_relative
- def get_package_include(self) -> Optional["InlineTable"]:
+ def get_package_include(self) -> InlineTable | None:
package = inline_table()
include = self._package_path_relative.parts[0]
@@ -112,9 +112,7 @@ def create(self, path: Path, with_tests: bool = True) -> None:
self._write_poetry(path)
- def generate_poetry_content(
- self, original: Optional["PyProjectTOML"] = None
- ) -> str:
+ def generate_poetry_content(self, original: PyProjectTOML | None = None) -> str:
template = POETRY_DEFAULT
content = loads(template)
diff --git a/src/poetry/layouts/src.py b/src/poetry/layouts/src.py
index be26fde9daa..fbaee68d0a7 100644
--- a/src/poetry/layouts/src.py
+++ b/src/poetry/layouts/src.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from pathlib import Path
from poetry.layouts.layout import Layout
diff --git a/src/poetry/locations.py b/src/poetry/locations.py
index 035a9a66e94..5312619a02e 100644
--- a/src/poetry/locations.py
+++ b/src/poetry/locations.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
from pathlib import Path
diff --git a/src/poetry/masonry/api.py b/src/poetry/masonry/api.py
index 417def2c834..807585aee05 100644
--- a/src/poetry/masonry/api.py
+++ b/src/poetry/masonry/api.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.core.masonry.api import build_sdist
from poetry.core.masonry.api import build_wheel
from poetry.core.masonry.api import get_requires_for_build_sdist
diff --git a/src/poetry/masonry/builders/__init__.py b/src/poetry/masonry/builders/__init__.py
index 303e50ceb34..ea5ca59a998 100644
--- a/src/poetry/masonry/builders/__init__.py
+++ b/src/poetry/masonry/builders/__init__.py
@@ -1 +1,3 @@
+from __future__ import annotations
+
from poetry.masonry.builders.editable import EditableBuilder
diff --git a/src/poetry/masonry/builders/editable.py b/src/poetry/masonry/builders/editable.py
index 12342ba429f..0697115b8c9 100644
--- a/src/poetry/masonry/builders/editable.py
+++ b/src/poetry/masonry/builders/editable.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import hashlib
import os
import shutil
@@ -5,7 +7,6 @@
from base64 import urlsafe_b64encode
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import List
from poetry.core.masonry.builders.builder import Builder
from poetry.core.masonry.builders.sdist import SdistBuilder
@@ -39,7 +40,7 @@
class EditableBuilder(Builder):
- def __init__(self, poetry: "Poetry", env: "Env", io: "IO") -> None:
+ def __init__(self, poetry: Poetry, env: Env, io: IO) -> None:
super().__init__(poetry)
self._env = env
@@ -109,7 +110,7 @@ def _setup_build(self) -> None:
if not has_setup:
os.remove(str(setup))
- def _add_pth(self) -> List[Path]:
+ def _add_pth(self) -> list[Path]:
paths = {
include.base.resolve().as_posix()
for include in self._module.includes
@@ -147,7 +148,7 @@ def _add_pth(self) -> List[Path]:
)
return []
- def _add_scripts(self) -> List[Path]:
+ def _add_scripts(self) -> list[Path]:
added = []
entry_points = self.convert_entry_points()
@@ -202,7 +203,7 @@ def _add_scripts(self) -> List[Path]:
return added
- def _add_dist_info(self, added_files: List[Path]) -> None:
+ def _add_dist_info(self, added_files: list[Path]) -> None:
from poetry.core.masonry.builders.wheel import WheelBuilder
added_files = added_files[:]
diff --git a/src/poetry/mixology/__init__.py b/src/poetry/mixology/__init__.py
index 899adbdbe63..0bf36495696 100644
--- a/src/poetry/mixology/__init__.py
+++ b/src/poetry/mixology/__init__.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
from poetry.mixology.version_solver import VersionSolver
@@ -14,11 +14,11 @@
def resolve_version(
- root: "ProjectPackage",
- provider: "Provider",
- locked: Dict[str, "DependencyPackage"] = None,
- use_latest: List[str] = None,
-) -> "SolverResult":
+ root: ProjectPackage,
+ provider: Provider,
+ locked: dict[str, DependencyPackage] = None,
+ use_latest: list[str] = None,
+) -> SolverResult:
solver = VersionSolver(root, provider, locked=locked, use_latest=use_latest)
return solver.solve()
diff --git a/src/poetry/mixology/assignment.py b/src/poetry/mixology/assignment.py
index d71d1403dc9..8e90266aa3e 100644
--- a/src/poetry/mixology/assignment.py
+++ b/src/poetry/mixology/assignment.py
@@ -1,6 +1,7 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from typing import Any
-from typing import Optional
from poetry.mixology.term import Term
@@ -19,11 +20,11 @@ class Assignment(Term):
def __init__(
self,
- dependency: "Dependency",
+ dependency: Dependency,
is_positive: bool,
decision_level: int,
index: int,
- cause: Optional["Incompatibility"] = None,
+ cause: Incompatibility | None = None,
) -> None:
super().__init__(dependency, is_positive)
@@ -40,13 +41,11 @@ def index(self) -> int:
return self._index
@property
- def cause(self) -> "Incompatibility":
+ def cause(self) -> Incompatibility:
return self._cause
@classmethod
- def decision(
- cls, package: "Package", decision_level: int, index: int
- ) -> "Assignment":
+ def decision(cls, package: Package, decision_level: int, index: int) -> Assignment:
return cls(package.to_dependency(), True, decision_level, index)
@classmethod
@@ -54,10 +53,10 @@ def derivation(
cls,
dependency: Any,
is_positive: bool,
- cause: "Incompatibility",
+ cause: Incompatibility,
decision_level: int,
index: int,
- ) -> "Assignment":
+ ) -> Assignment:
return cls(dependency, is_positive, decision_level, index, cause)
def is_decision(self) -> bool:
diff --git a/src/poetry/mixology/failure.py b/src/poetry/mixology/failure.py
index 8060e57e9d0..72229939aa4 100644
--- a/src/poetry/mixology/failure.py
+++ b/src/poetry/mixology/failure.py
@@ -1,8 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Tuple
from poetry.core.semver.helpers import parse_constraint
@@ -15,7 +13,7 @@
class SolveFailure(Exception):
- def __init__(self, incompatibility: "Incompatibility") -> None:
+ def __init__(self, incompatibility: Incompatibility) -> None:
self._incompatibility = incompatibility
@property
@@ -27,11 +25,11 @@ def __str__(self) -> str:
class _Writer:
- def __init__(self, root: "Incompatibility") -> None:
+ def __init__(self, root: Incompatibility) -> None:
self._root = root
- self._derivations: Dict["Incompatibility", int] = {}
- self._lines: List[Tuple[str, Optional[int]]] = []
- self._line_numbers: Dict["Incompatibility", int] = {}
+ self._derivations: dict[Incompatibility, int] = {}
+ self._lines: list[tuple[str, int | None]] = []
+ self._line_numbers: dict[Incompatibility, int] = {}
self._count_derivations(self._root)
@@ -97,7 +95,7 @@ def write(self) -> str:
return "\n".join(buffer)
def _write(
- self, incompatibility: "Incompatibility", message: str, numbered: bool = False
+ self, incompatibility: Incompatibility, message: str, numbered: bool = False
) -> None:
if numbered:
number = len(self._line_numbers) + 1
@@ -108,8 +106,8 @@ def _write(
def _visit(
self,
- incompatibility: "Incompatibility",
- details_for_incompatibility: Dict,
+ incompatibility: Incompatibility,
+ details_for_incompatibility: dict,
conclusion: bool = False,
) -> None:
numbered = conclusion or self._derivations[incompatibility] > 1
@@ -237,7 +235,7 @@ def _visit(
numbered=numbered,
)
- def _is_collapsible(self, incompatibility: "Incompatibility") -> bool:
+ def _is_collapsible(self, incompatibility: Incompatibility) -> bool:
if self._derivations[incompatibility] > 1:
return False
@@ -265,7 +263,7 @@ def _is_single_line(self, cause: ConflictCause) -> bool:
cause.other.cause, ConflictCause
)
- def _count_derivations(self, incompatibility: "Incompatibility") -> None:
+ def _count_derivations(self, incompatibility: Incompatibility) -> None:
if incompatibility in self._derivations:
self._derivations[incompatibility] += 1
else:
diff --git a/src/poetry/mixology/incompatibility.py b/src/poetry/mixology/incompatibility.py
index c8ff36ad374..37d3992d43f 100644
--- a/src/poetry/mixology/incompatibility.py
+++ b/src/poetry/mixology/incompatibility.py
@@ -1,10 +1,8 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from typing import Callable
-from typing import Dict
from typing import Iterator
-from typing import List
-from typing import Optional
-from typing import Union
from poetry.mixology.incompatibility_cause import ConflictCause
from poetry.mixology.incompatibility_cause import DependencyCause
@@ -21,7 +19,7 @@
class Incompatibility:
- def __init__(self, terms: List["Term"], cause: "IncompatibilityCause") -> None:
+ def __init__(self, terms: list[Term], cause: IncompatibilityCause) -> None:
# Remove the root package from generated incompatibilities, since it will
# always be satisfied. This makes error reporting clearer, and may also
# make solving more efficient.
@@ -43,7 +41,7 @@ def __init__(self, terms: List["Term"], cause: "IncompatibilityCause") -> None:
or terms[0].dependency.complete_name == terms[-1].dependency.complete_name
):
# Coalesce multiple terms about the same package if possible.
- by_name: Dict[str, Dict[str, "Term"]] = {}
+ by_name: dict[str, dict[str, Term]] = {}
for term in terms:
if term.dependency.complete_name not in by_name:
by_name[term.dependency.complete_name] = {}
@@ -81,27 +79,27 @@ def __init__(self, terms: List["Term"], cause: "IncompatibilityCause") -> None:
self._cause = cause
@property
- def terms(self) -> List["Term"]:
+ def terms(self) -> list[Term]:
return self._terms
@property
def cause(
self,
- ) -> Union[
- RootCause,
- NoVersionsCause,
- DependencyCause,
- ConflictCause,
- PythonCause,
- PlatformCause,
- PackageNotFoundCause,
- ]:
+ ) -> (
+ RootCause
+ | NoVersionsCause
+ | DependencyCause
+ | ConflictCause
+ | PythonCause
+ | PlatformCause
+ | PackageNotFoundCause
+ ):
return self._cause
@property
def external_incompatibilities(
self,
- ) -> Iterator[Union[ConflictCause, "Incompatibility"]]:
+ ) -> Iterator[ConflictCause | Incompatibility]:
"""
Returns all external incompatibilities in this incompatibility's
derivation graph.
@@ -226,10 +224,10 @@ def __str__(self) -> str:
def and_to_string(
self,
- other: "Incompatibility",
+ other: Incompatibility,
details: dict,
- this_line: Optional[int],
- other_line: Optional[int],
+ this_line: int | None,
+ other_line: int | None,
) -> str:
requires_both = self._try_requires_both(other, details, this_line, other_line)
if requires_both is not None:
@@ -260,11 +258,11 @@ def and_to_string(
def _try_requires_both(
self,
- other: "Incompatibility",
+ other: Incompatibility,
details: dict,
- this_line: Optional[int],
- other_line: Optional[int],
- ) -> Optional[str]:
+ this_line: int | None,
+ other_line: int | None,
+ ) -> str | None:
if len(self._terms) == 1 or len(other.terms) == 1:
return None
@@ -309,8 +307,8 @@ def _try_requires_both(
return "".join(buffer)
def _try_requires_through(
- self, other: "Incompatibility", details: dict, this_line: int, other_line: int
- ) -> Optional[str]:
+ self, other: Incompatibility, details: dict, this_line: int, other_line: int
+ ) -> str | None:
if len(self._terms) == 1 or len(other.terms) == 1:
return None
@@ -387,8 +385,8 @@ def _try_requires_through(
return "".join(buffer)
def _try_requires_forbidden(
- self, other: "Incompatibility", details: dict, this_line: int, other_line: int
- ) -> Optional[str]:
+ self, other: Incompatibility, details: dict, this_line: int, other_line: int
+ ) -> str | None:
if len(self._terms) != 1 and len(other.terms) != 1:
return None
@@ -442,7 +440,7 @@ def _try_requires_forbidden(
return "".join(buffer)
- def _terse(self, term: "Term", allow_every: bool = False) -> str:
+ def _terse(self, term: Term, allow_every: bool = False) -> str:
if allow_every and term.constraint.is_any():
return f"every version of {term.dependency.complete_name}"
@@ -451,9 +449,7 @@ def _terse(self, term: "Term", allow_every: bool = False) -> str:
return f"{term.dependency.pretty_name} ({term.dependency.pretty_constraint})"
- def _single_term_where(
- self, callable: Callable[["Term"], bool]
- ) -> Optional["Term"]:
+ def _single_term_where(self, callable: Callable[[Term], bool]) -> Term | None:
found = None
for term in self._terms:
if not callable(term):
diff --git a/src/poetry/mixology/incompatibility_cause.py b/src/poetry/mixology/incompatibility_cause.py
index 3267be56d7a..568287d55f5 100644
--- a/src/poetry/mixology/incompatibility_cause.py
+++ b/src/poetry/mixology/incompatibility_cause.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
@@ -32,16 +34,16 @@ class ConflictCause(IncompatibilityCause):
during conflict resolution.
"""
- def __init__(self, conflict: "Incompatibility", other: "Incompatibility") -> None:
+ def __init__(self, conflict: Incompatibility, other: Incompatibility) -> None:
self._conflict = conflict
self._other = other
@property
- def conflict(self) -> "Incompatibility":
+ def conflict(self) -> Incompatibility:
return self._conflict
@property
- def other(self) -> "Incompatibility":
+ def other(self) -> Incompatibility:
return self._other
def __str__(self) -> str:
diff --git a/src/poetry/mixology/partial_solution.py b/src/poetry/mixology/partial_solution.py
index ed5aee4293e..e02f413b7a9 100644
--- a/src/poetry/mixology/partial_solution.py
+++ b/src/poetry/mixology/partial_solution.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
from poetry.mixology.assignment import Assignment
from poetry.mixology.set_relation import SetRelation
@@ -27,16 +27,16 @@ class PartialSolution:
def __init__(self) -> None:
# The assignments that have been made so far, in the order they were
# assigned.
- self._assignments: List[Assignment] = []
+ self._assignments: list[Assignment] = []
# The decisions made for each package.
- self._decisions: Dict[str, "Package"] = {}
+ self._decisions: dict[str, Package] = {}
# The intersection of all positive Assignments for each package, minus any
# negative Assignments that refer to that package.
#
# This is derived from self._assignments.
- self._positive: Dict[str, "Term"] = {}
+ self._positive: dict[str, Term] = {}
# The union of all negative Assignments for each package.
#
@@ -44,7 +44,7 @@ def __init__(self) -> None:
# map.
#
# This is derived from self._assignments.
- self._negative: Dict[str, Dict[str, "Term"]] = {}
+ self._negative: dict[str, dict[str, Term]] = {}
# The number of distinct solutions that have been attempted so far.
self._attempted_solutions = 1
@@ -53,7 +53,7 @@ def __init__(self) -> None:
self._backtracking = False
@property
- def decisions(self) -> List["Package"]:
+ def decisions(self) -> list[Package]:
return list(self._decisions.values())
@property
@@ -65,14 +65,14 @@ def attempted_solutions(self) -> int:
return self._attempted_solutions
@property
- def unsatisfied(self) -> List["Dependency"]:
+ def unsatisfied(self) -> list[Dependency]:
return [
term.dependency
for term in self._positive.values()
if term.dependency.complete_name not in self._decisions
]
- def decide(self, package: "Package") -> None:
+ def decide(self, package: Package) -> None:
"""
Adds an assignment of package as a decision
and increments the decision level.
@@ -92,7 +92,7 @@ def decide(self, package: "Package") -> None:
)
def derive(
- self, dependency: "Dependency", is_positive: bool, cause: "Incompatibility"
+ self, dependency: Dependency, is_positive: bool, cause: Incompatibility
) -> None:
"""
Adds an assignment of package as a derivation.
@@ -170,7 +170,7 @@ def _register(self, assignment: Assignment) -> None:
self._negative[name][ref] = term
- def satisfier(self, term: "Term") -> Assignment:
+ def satisfier(self, term: Term) -> Assignment:
"""
Returns the first Assignment in this solution such that the sublist of
assignments up to and including that entry collectively satisfies term.
@@ -203,10 +203,10 @@ def satisfier(self, term: "Term") -> Assignment:
raise RuntimeError(f"[BUG] {term} is not satisfied.")
- def satisfies(self, term: "Term") -> bool:
+ def satisfies(self, term: Term) -> bool:
return self.relation(term) == SetRelation.SUBSET
- def relation(self, term: "Term") -> int:
+ def relation(self, term: Term) -> int:
positive = self._positive.get(term.dependency.complete_name)
if positive is not None:
return positive.relation(term)
diff --git a/src/poetry/mixology/result.py b/src/poetry/mixology/result.py
index d2ef1a2dade..b4db7acb6d5 100644
--- a/src/poetry/mixology/result.py
+++ b/src/poetry/mixology/result.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
if TYPE_CHECKING:
@@ -10,8 +11,8 @@
class SolverResult:
def __init__(
self,
- root: "ProjectPackage",
- packages: List["Package"],
+ root: ProjectPackage,
+ packages: list[Package],
attempted_solutions: int,
) -> None:
self._root = root
@@ -19,7 +20,7 @@ def __init__(
self._attempted_solutions = attempted_solutions
@property
- def packages(self) -> List["Package"]:
+ def packages(self) -> list[Package]:
return self._packages
@property
diff --git a/src/poetry/mixology/set_relation.py b/src/poetry/mixology/set_relation.py
index 4bd333bc019..a71e826193e 100644
--- a/src/poetry/mixology/set_relation.py
+++ b/src/poetry/mixology/set_relation.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+
class SetRelation:
"""
An enum of possible relationships between two sets.
diff --git a/src/poetry/mixology/solutions/providers/__init__.py b/src/poetry/mixology/solutions/providers/__init__.py
index 1dd2be8f590..9470041fd57 100644
--- a/src/poetry/mixology/solutions/providers/__init__.py
+++ b/src/poetry/mixology/solutions/providers/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.mixology.solutions.providers.python_requirement_solution_provider import (
PythonRequirementSolutionProvider,
)
diff --git a/src/poetry/mixology/solutions/providers/python_requirement_solution_provider.py b/src/poetry/mixology/solutions/providers/python_requirement_solution_provider.py
index 4b0ef62cc95..796dd810416 100644
--- a/src/poetry/mixology/solutions/providers/python_requirement_solution_provider.py
+++ b/src/poetry/mixology/solutions/providers/python_requirement_solution_provider.py
@@ -1,7 +1,8 @@
+from __future__ import annotations
+
import re
from typing import TYPE_CHECKING
-from typing import List
from crashtest.contracts.has_solutions_for_exception import HasSolutionsForException
@@ -25,7 +26,7 @@ def can_solve(self, exception: Exception) -> bool:
return bool(m)
- def get_solutions(self, exception: Exception) -> List["Solution"]:
+ def get_solutions(self, exception: Exception) -> list[Solution]:
from poetry.mixology.solutions.solutions.python_requirement_solution import (
PythonRequirementSolution,
)
diff --git a/src/poetry/mixology/solutions/solutions/__init__.py b/src/poetry/mixology/solutions/solutions/__init__.py
index 7aa5a9e0078..51b8449071b 100644
--- a/src/poetry/mixology/solutions/solutions/__init__.py
+++ b/src/poetry/mixology/solutions/solutions/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.mixology.solutions.solutions.python_requirement_solution import (
PythonRequirementSolution,
)
diff --git a/src/poetry/mixology/solutions/solutions/python_requirement_solution.py b/src/poetry/mixology/solutions/solutions/python_requirement_solution.py
index 5e97aade791..7c3623921f7 100644
--- a/src/poetry/mixology/solutions/solutions/python_requirement_solution.py
+++ b/src/poetry/mixology/solutions/solutions/python_requirement_solution.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
from crashtest.contracts.solution import Solution
@@ -9,7 +10,7 @@
class PythonRequirementSolution(Solution):
- def __init__(self, exception: "PackageNotFoundCause") -> None:
+ def __init__(self, exception: PackageNotFoundCause) -> None:
from poetry.core.semver.helpers import parse_constraint
from poetry.mixology.incompatibility_cause import PythonCause
@@ -54,7 +55,7 @@ def solution_description(self) -> str:
return self._description
@property
- def documentation_links(self) -> List[str]:
+ def documentation_links(self) -> list[str]:
return [
"https://python-poetry.org/docs/dependency-specification/#python-restricted-dependencies", # noqa: E501
"https://python-poetry.org/docs/dependency-specification/#using-environment-markers", # noqa: E501
diff --git a/src/poetry/mixology/term.py b/src/poetry/mixology/term.py
index df30ce621ed..a8b83b80273 100644
--- a/src/poetry/mixology/term.py
+++ b/src/poetry/mixology/term.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
from poetry.mixology.set_relation import SetRelation
@@ -17,26 +18,26 @@ class Term:
See https://github.com/dart-lang/pub/tree/master/doc/solver.md#term.
"""
- def __init__(self, dependency: "Dependency", is_positive: bool) -> None:
+ def __init__(self, dependency: Dependency, is_positive: bool) -> None:
self._dependency = dependency
self._positive = is_positive
@property
- def inverse(self) -> "Term":
+ def inverse(self) -> Term:
return Term(self._dependency, not self.is_positive())
@property
- def dependency(self) -> "Dependency":
+ def dependency(self) -> Dependency:
return self._dependency
@property
- def constraint(self) -> "VersionTypes":
+ def constraint(self) -> VersionTypes:
return self._dependency.constraint
def is_positive(self) -> bool:
return self._positive
- def satisfies(self, other: "Term") -> bool:
+ def satisfies(self, other: Term) -> bool:
"""
Returns whether this term satisfies another.
"""
@@ -45,7 +46,7 @@ def satisfies(self, other: "Term") -> bool:
and self.relation(other) == SetRelation.SUBSET
)
- def relation(self, other: "Term") -> int:
+ def relation(self, other: Term) -> int:
"""
Returns the relationship between the package versions
allowed by this term and another.
@@ -107,7 +108,7 @@ def relation(self, other: "Term") -> int:
# not foo ^1.5.0 is a superset of not foo ^1.0.0
return SetRelation.OVERLAPPING
- def intersect(self, other: "Term") -> Optional["Term"]:
+ def intersect(self, other: Term) -> Term | None:
"""
Returns a Term that represents the packages
allowed by both this term and another
@@ -139,14 +140,14 @@ def intersect(self, other: "Term") -> Optional["Term"]:
else:
return None
- def difference(self, other: "Term") -> "Term":
+ def difference(self, other: Term) -> Term:
"""
Returns a Term that represents packages
allowed by this term and not by the other
"""
return self.intersect(other.inverse)
- def _compatible_dependency(self, other: "Dependency") -> bool:
+ def _compatible_dependency(self, other: Dependency) -> bool:
return (
self.dependency.is_root
or other.is_root
@@ -154,8 +155,8 @@ def _compatible_dependency(self, other: "Dependency") -> bool:
)
def _non_empty_term(
- self, constraint: "VersionTypes", is_positive: bool
- ) -> Optional["Term"]:
+ self, constraint: VersionTypes, is_positive: bool
+ ) -> Term | None:
if constraint.is_empty():
return None
diff --git a/src/poetry/mixology/version_solver.py b/src/poetry/mixology/version_solver.py
index 555f9c02324..0be0bf04220 100644
--- a/src/poetry/mixology/version_solver.py
+++ b/src/poetry/mixology/version_solver.py
@@ -1,11 +1,8 @@
+from __future__ import annotations
+
import time
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Tuple
-from typing import Union
from poetry.core.packages.dependency import Dependency
@@ -42,10 +39,10 @@ class VersionSolver:
def __init__(
self,
- root: "ProjectPackage",
- provider: "Provider",
- locked: Dict[str, "Package"] = None,
- use_latest: List[str] = None,
+ root: ProjectPackage,
+ provider: Provider,
+ locked: dict[str, Package] = None,
+ use_latest: list[str] = None,
):
self._root = root
self._provider = provider
@@ -56,7 +53,7 @@ def __init__(
self._use_latest = use_latest
- self._incompatibilities: Dict[str, List[Incompatibility]] = {}
+ self._incompatibilities: dict[str, list[Incompatibility]] = {}
self._solution = PartialSolution()
@property
@@ -128,7 +125,7 @@ def _propagate(self, package: str) -> None:
def _propagate_incompatibility(
self, incompatibility: Incompatibility
- ) -> Union[str, object, None]:
+ ) -> str | object | None:
"""
If incompatibility is almost satisfied by _solution, adds the
negation of the unsatisfied term to _solution.
@@ -307,7 +304,7 @@ def _resolve_conflict(self, incompatibility: Incompatibility) -> Incompatibility
raise SolveFailure(incompatibility)
- def _choose_package_version(self) -> Optional[str]:
+ def _choose_package_version(self) -> str | None:
"""
Tries to select a version of a required package.
@@ -321,7 +318,7 @@ def _choose_package_version(self) -> Optional[str]:
# Prefer packages with as few remaining versions as possible,
# so that if a conflict is necessary it's forced quickly.
- def _get_min(dependency: Dependency) -> Tuple[bool, int]:
+ def _get_min(dependency: Dependency) -> tuple[bool, int]:
if dependency.name in self._use_latest:
# If we're forced to use the latest version of a package, it effectively
# only has one version to choose from.
@@ -438,7 +435,7 @@ def _add_incompatibility(self, incompatibility: Incompatibility) -> None:
incompatibility
)
- def _get_locked(self, dependency: Dependency) -> Optional["Package"]:
+ def _get_locked(self, dependency: Dependency) -> Package | None:
if dependency.name in self._use_latest:
return None
diff --git a/src/poetry/packages/__init__.py b/src/poetry/packages/__init__.py
index e699ca73695..719e44d963b 100644
--- a/src/poetry/packages/__init__.py
+++ b/src/poetry/packages/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.packages.dependency_package import DependencyPackage
from poetry.packages.locker import Locker
from poetry.packages.package_collection import PackageCollection
diff --git a/src/poetry/packages/dependency_package.py b/src/poetry/packages/dependency_package.py
index aaf102f0b32..f020ac5d130 100644
--- a/src/poetry/packages/dependency_package.py
+++ b/src/poetry/packages/dependency_package.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from typing import Any
-from typing import List
-from typing import Union
if TYPE_CHECKING:
@@ -10,25 +10,25 @@
class DependencyPackage:
- def __init__(self, dependency: "Dependency", package: "Package") -> None:
+ def __init__(self, dependency: Dependency, package: Package) -> None:
self._dependency = dependency
self._package = package
@property
- def dependency(self) -> "Dependency":
+ def dependency(self) -> Dependency:
return self._dependency
@property
- def package(self) -> "Package":
+ def package(self) -> Package:
return self._package
- def clone(self) -> "DependencyPackage":
+ def clone(self) -> DependencyPackage:
return self.__class__(self._dependency, self._package.clone())
- def with_features(self, features: List[str]) -> "DependencyPackage":
+ def with_features(self, features: list[str]) -> DependencyPackage:
return self.__class__(self._dependency, self._package.with_features(features))
- def without_features(self) -> "DependencyPackage":
+ def without_features(self) -> DependencyPackage:
return self.with_features([])
def __getattr__(self, name: str) -> Any:
@@ -49,7 +49,7 @@ def __repr__(self) -> str:
def __hash__(self) -> int:
return hash(self._package)
- def __eq__(self, other: Union["Package", "DependencyPackage"]) -> bool:
+ def __eq__(self, other: Package | DependencyPackage) -> bool:
if isinstance(other, DependencyPackage):
other = other.package
diff --git a/src/poetry/packages/locker.py b/src/poetry/packages/locker.py
index 4cf56b9ae93..7f1913c8224 100644
--- a/src/poetry/packages/locker.py
+++ b/src/poetry/packages/locker.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import json
import logging
import os
@@ -7,15 +9,9 @@
from hashlib import sha256
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
from typing import Iterable
from typing import Iterator
-from typing import List
-from typing import Optional
from typing import Sequence
-from typing import Set
-from typing import Tuple
-from typing import Union
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.package import Package
@@ -49,7 +45,7 @@ class Locker:
_relevant_keys = ["dependencies", "group", "source", "extras"]
- def __init__(self, lock: Union[str, Path], local_config: dict) -> None:
+ def __init__(self, lock: str | Path, local_config: dict) -> None:
self._lock = TOMLFile(lock)
self._local_config = local_config
self._lock_data = None
@@ -60,7 +56,7 @@ def lock(self) -> TOMLFile:
return self._lock
@property
- def lock_data(self) -> "TOMLDocument":
+ def lock_data(self) -> TOMLDocument:
if self._lock_data is None:
self._lock_data = self._get_lock_data()
@@ -87,7 +83,7 @@ def is_fresh(self) -> bool:
return False
- def locked_repository(self, with_dev_reqs: bool = False) -> "Repository":
+ def locked_repository(self, with_dev_reqs: bool = False) -> Repository:
"""
Searches and returns a repository of locked packages.
"""
@@ -204,8 +200,8 @@ def locked_repository(self, with_dev_reqs: bool = False) -> "Repository":
@staticmethod
def __get_locked_package(
- _dependency: Dependency, packages_by_name: Dict[str, List[Package]]
- ) -> Optional[Package]:
+ _dependency: Dependency, packages_by_name: dict[str, list[Package]]
+ ) -> Package | None:
"""
Internal helper to identify corresponding locked package using dependency
version constraints.
@@ -218,13 +214,13 @@ def __get_locked_package(
@classmethod
def __walk_dependency_level(
cls,
- dependencies: List[Dependency],
+ dependencies: list[Dependency],
level: int,
pinned_versions: bool,
- packages_by_name: Dict[str, List[Package]],
- project_level_dependencies: Set[str],
- nested_dependencies: Dict[Tuple[str, str], Dependency],
- ) -> Dict[Tuple[str, str], Dependency]:
+ packages_by_name: dict[str, list[Package]],
+ project_level_dependencies: set[str],
+ nested_dependencies: dict[tuple[str, str], Dependency],
+ ) -> dict[tuple[str, str], Dependency]:
if not dependencies:
return nested_dependencies
@@ -286,8 +282,8 @@ def __walk_dependency_level(
@classmethod
def get_project_dependencies(
cls,
- project_requires: List[Dependency],
- locked_packages: List[Package],
+ project_requires: list[Dependency],
+ locked_packages: list[Package],
pinned_versions: bool = False,
with_nested: bool = False,
) -> Iterable[Dependency]:
@@ -346,9 +342,9 @@ def get_project_dependencies(
def get_project_dependency_packages(
self,
- project_requires: List[Dependency],
+ project_requires: list[Dependency],
dev: bool = False,
- extras: Optional[Union[bool, Sequence[str]]] = None,
+ extras: bool | Sequence[str] | None = None,
) -> Iterator[DependencyPackage]:
repository = self.locked_repository(with_dev_reqs=dev)
@@ -397,7 +393,7 @@ def get_project_dependency_packages(
yield DependencyPackage(dependency=dependency, package=package)
- def set_lock_data(self, root: Package, packages: List[Package]) -> bool:
+ def set_lock_data(self, root: Package, packages: list[Package]) -> bool:
files = table()
packages = self._lock_packages(packages)
# Retrieving hashes
@@ -440,7 +436,7 @@ def set_lock_data(self, root: Package, packages: List[Package]) -> bool:
return False
- def _write_lock_data(self, data: "TOMLDocument") -> None:
+ def _write_lock_data(self, data: TOMLDocument) -> None:
self.lock.write(data)
# Checking lock file data consistency
@@ -465,7 +461,7 @@ def _get_content_hash(self) -> str:
return content_hash
- def _get_lock_data(self) -> "TOMLDocument":
+ def _get_lock_data(self) -> TOMLDocument:
if not self._lock.exists():
raise RuntimeError("No lockfile found. Unable to read locked packages")
@@ -498,7 +494,7 @@ def _get_lock_data(self) -> "TOMLDocument":
return lock_data
- def _lock_packages(self, packages: List[Package]) -> list:
+ def _lock_packages(self, packages: list[Package]) -> list:
locked = []
for package in sorted(packages, key=lambda x: x.name):
@@ -619,5 +615,5 @@ def _dump_package(self, package: Package) -> dict:
class NullLocker(Locker):
- def set_lock_data(self, root: Package, packages: List[Package]) -> bool:
+ def set_lock_data(self, root: Package, packages: list[Package]) -> bool:
pass
diff --git a/src/poetry/packages/package_collection.py b/src/poetry/packages/package_collection.py
index cc7ae51fd94..0a4213e9f43 100644
--- a/src/poetry/packages/package_collection.py
+++ b/src/poetry/packages/package_collection.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Union
from poetry.packages.dependency_package import DependencyPackage
@@ -13,8 +13,8 @@
class PackageCollection(list):
def __init__(
self,
- dependency: "Dependency",
- packages: List[Union["Package", DependencyPackage]] = None,
+ dependency: Dependency,
+ packages: list[Package | DependencyPackage] = None,
) -> None:
self._dependency = dependency
@@ -26,7 +26,7 @@ def __init__(
for package in packages:
self.append(package)
- def append(self, package: Union["Package", DependencyPackage]) -> None:
+ def append(self, package: Package | DependencyPackage) -> None:
if isinstance(package, DependencyPackage):
package = package.package
diff --git a/src/poetry/packages/project_package.py b/src/poetry/packages/project_package.py
index cf7e2c3ffa8..698c3aa1822 100644
--- a/src/poetry/packages/project_package.py
+++ b/src/poetry/packages/project_package.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
-from typing import Union
from poetry.core.packages.project_package import ProjectPackage as _ProjectPackage
@@ -11,7 +11,7 @@
class ProjectPackage(_ProjectPackage):
def set_version(
- self, version: Union[str, "Version"], pretty_version: Optional[str] = None
+ self, version: str | Version, pretty_version: str | None = None
) -> None:
from poetry.core.semver.version import Version
diff --git a/src/poetry/plugins/__init__.py b/src/poetry/plugins/__init__.py
index 10a799d8d38..bf62b4e3190 100644
--- a/src/poetry/plugins/__init__.py
+++ b/src/poetry/plugins/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.plugins.application_plugin import ApplicationPlugin
from poetry.plugins.plugin import Plugin
diff --git a/src/poetry/plugins/application_plugin.py b/src/poetry/plugins/application_plugin.py
index bcc557d8f9d..d7ebc55b416 100644
--- a/src/poetry/plugins/application_plugin.py
+++ b/src/poetry/plugins/application_plugin.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.plugins.base_plugin import BasePlugin
@@ -14,5 +16,5 @@ class ApplicationPlugin(BasePlugin):
type = "application.plugin"
- def activate(self, application: "Application") -> None:
+ def activate(self, application: Application) -> None:
raise NotImplementedError()
diff --git a/src/poetry/plugins/base_plugin.py b/src/poetry/plugins/base_plugin.py
index de42071b4dc..2366db07964 100644
--- a/src/poetry/plugins/base_plugin.py
+++ b/src/poetry/plugins/base_plugin.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+
class BasePlugin:
"""
Base class for all plugin types
diff --git a/src/poetry/plugins/plugin.py b/src/poetry/plugins/plugin.py
index 48fcf9a1eb5..38fb149bc07 100644
--- a/src/poetry/plugins/plugin.py
+++ b/src/poetry/plugins/plugin.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.plugins.base_plugin import BasePlugin
@@ -18,5 +20,5 @@ class Plugin(BasePlugin):
type = "plugin"
- def activate(self, poetry: "Poetry", io: "IO") -> None:
+ def activate(self, poetry: Poetry, io: IO) -> None:
raise NotImplementedError()
diff --git a/src/poetry/plugins/plugin_manager.py b/src/poetry/plugins/plugin_manager.py
index c184c053beb..3354b671df0 100644
--- a/src/poetry/plugins/plugin_manager.py
+++ b/src/poetry/plugins/plugin_manager.py
@@ -1,7 +1,8 @@
+from __future__ import annotations
+
import logging
from typing import Any
-from typing import List
import entrypoints
@@ -20,7 +21,7 @@ class PluginManager:
def __init__(self, type: str, disable_plugins: bool = False) -> None:
self._type = type
self._disable_plugins = disable_plugins
- self._plugins: List[Plugin] = []
+ self._plugins: list[Plugin] = []
def load_plugins(self) -> None:
if self._disable_plugins:
@@ -31,7 +32,7 @@ def load_plugins(self) -> None:
for entrypoint in plugin_entrypoints:
self._load_plugin_entrypoint(entrypoint)
- def get_plugin_entry_points(self) -> List[entrypoints.EntryPoint]:
+ def get_plugin_entry_points(self) -> list[entrypoints.EntryPoint]:
return entrypoints.get_group_all(f"poetry.{self._type}")
def add_plugin(self, plugin: Plugin) -> None:
diff --git a/src/poetry/poetry.py b/src/poetry/poetry.py
index eb3e4b50c41..706cec314be 100644
--- a/src/poetry/poetry.py
+++ b/src/poetry/poetry.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
from poetry.core.poetry import Poetry as BasePoetry
@@ -25,11 +25,11 @@ class Poetry(BasePoetry):
def __init__(
self,
- file: "Path",
+ file: Path,
local_config: dict,
- package: "ProjectPackage",
- locker: "Locker",
- config: "Config",
+ package: ProjectPackage,
+ locker: Locker,
+ config: Config,
):
from poetry.repositories.pool import Pool
@@ -38,41 +38,41 @@ def __init__(
self._locker = locker
self._config = config
self._pool = Pool()
- self._plugin_manager: Optional["PluginManager"] = None
+ self._plugin_manager: PluginManager | None = None
@property
- def locker(self) -> "Locker":
+ def locker(self) -> Locker:
return self._locker
@property
- def pool(self) -> "Pool":
+ def pool(self) -> Pool:
return self._pool
@property
- def config(self) -> "Config":
+ def config(self) -> Config:
return self._config
- def set_locker(self, locker: "Locker") -> "Poetry":
+ def set_locker(self, locker: Locker) -> Poetry:
self._locker = locker
return self
- def set_pool(self, pool: "Pool") -> "Poetry":
+ def set_pool(self, pool: Pool) -> Poetry:
self._pool = pool
return self
- def set_config(self, config: "Config") -> "Poetry":
+ def set_config(self, config: Config) -> Poetry:
self._config = config
return self
- def set_plugin_manager(self, plugin_manager: "PluginManager") -> "Poetry":
+ def set_plugin_manager(self, plugin_manager: PluginManager) -> Poetry:
self._plugin_manager = plugin_manager
return self
- def get_sources(self) -> List[Source]:
+ def get_sources(self) -> list[Source]:
return [
Source(**source)
for source in self.pyproject.poetry_config.get("source", [])
diff --git a/src/poetry/publishing/__init__.py b/src/poetry/publishing/__init__.py
index cf6b0f24789..c7aa27edb1c 100644
--- a/src/poetry/publishing/__init__.py
+++ b/src/poetry/publishing/__init__.py
@@ -1 +1,3 @@
+from __future__ import annotations
+
from poetry.publishing.publisher import Publisher
diff --git a/src/poetry/publishing/publisher.py b/src/poetry/publishing/publisher.py
index 5e44c931434..bf8b95f6d85 100644
--- a/src/poetry/publishing/publisher.py
+++ b/src/poetry/publishing/publisher.py
@@ -1,9 +1,8 @@
+from __future__ import annotations
+
import logging
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
-from typing import Union
from poetry.publishing.uploader import Uploader
from poetry.utils.authenticator import Authenticator
@@ -27,7 +26,7 @@ class Publisher:
Registers and publishes packages to remote repositories.
"""
- def __init__(self, poetry: "Poetry", io: Union["BufferedIO", "ConsoleIO"]) -> None:
+ def __init__(self, poetry: Poetry, io: BufferedIO | ConsoleIO) -> None:
self._poetry = poetry
self._package = poetry.package
self._io = io
@@ -35,16 +34,16 @@ def __init__(self, poetry: "Poetry", io: Union["BufferedIO", "ConsoleIO"]) -> No
self._authenticator = Authenticator(poetry.config, self._io)
@property
- def files(self) -> List["Path"]:
+ def files(self) -> list[Path]:
return self._uploader.files
def publish(
self,
- repository_name: Optional[str],
- username: Optional[str],
- password: Optional[str],
- cert: Optional["Path"] = None,
- client_cert: Optional["Path"] = None,
+ repository_name: str | None,
+ username: str | None,
+ password: str | None,
+ cert: Path | None = None,
+ client_cert: Path | None = None,
dry_run: bool = False,
) -> None:
if not repository_name:
diff --git a/src/poetry/publishing/uploader.py b/src/poetry/publishing/uploader.py
index f13df804fc0..d555fdb768a 100644
--- a/src/poetry/publishing/uploader.py
+++ b/src/poetry/publishing/uploader.py
@@ -1,13 +1,10 @@
+from __future__ import annotations
+
import hashlib
import io
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Tuple
-from typing import Union
import requests
@@ -38,7 +35,7 @@
class UploadError(Exception):
- def __init__(self, error: Union[ConnectionError, HTTPError, str]) -> None:
+ def __init__(self, error: ConnectionError | HTTPError | str) -> None:
if isinstance(error, HTTPError):
message = (
f"HTTP Error {error.response.status_code}: {error.response.reason}"
@@ -54,12 +51,12 @@ def __init__(self, error: Union[ConnectionError, HTTPError, str]) -> None:
class Uploader:
- def __init__(self, poetry: "Poetry", io: "NullIO") -> None:
+ def __init__(self, poetry: Poetry, io: NullIO) -> None:
self._poetry = poetry
self._package = poetry.package
self._io = io
- self._username: Optional[str] = None
- self._password: Optional[str] = None
+ self._username: str | None = None
+ self._password: str | None = None
@property
def user_agent(self) -> str:
@@ -77,7 +74,7 @@ def adapter(self) -> adapters.HTTPAdapter:
return adapters.HTTPAdapter(max_retries=retry)
@property
- def files(self) -> List["Path"]:
+ def files(self) -> list[Path]:
dist = self._poetry.file.parent / "dist"
version = normalize_version(self._package.version.text)
@@ -91,7 +88,7 @@ def files(self) -> List["Path"]:
return sorted(wheels + tars)
- def auth(self, username: Optional[str], password: Optional[str]) -> None:
+ def auth(self, username: str | None, password: str | None) -> None:
self._username = username
self._password = password
@@ -107,7 +104,7 @@ def make_session(self) -> requests.Session:
return session
- def get_auth(self) -> Optional[Tuple[str, str]]:
+ def get_auth(self) -> tuple[str, str] | None:
if self._username is None or self._password is None:
return None
@@ -116,8 +113,8 @@ def get_auth(self) -> Optional[Tuple[str, str]]:
def upload(
self,
url: str,
- cert: Optional["Path"] = None,
- client_cert: Optional["Path"] = None,
+ cert: Path | None = None,
+ client_cert: Path | None = None,
dry_run: bool = False,
) -> None:
session = self.make_session()
@@ -133,7 +130,7 @@ def upload(
finally:
session.close()
- def post_data(self, file: "Path") -> Dict[str, Any]:
+ def post_data(self, file: Path) -> dict[str, Any]:
meta = Metadata.from_package(self._package)
file_type = self._get_type(file)
@@ -153,11 +150,11 @@ def post_data(self, file: "Path") -> Dict[str, Any]:
md5_digest = md5_hash.hexdigest()
sha2_digest = sha256_hash.hexdigest()
- blake2_256_digest: Optional[str] = None
+ blake2_256_digest: str | None = None
if _has_blake2:
blake2_256_digest = blake2_256_hash.hexdigest()
- py_version: Optional[str] = None
+ py_version: str | None = None
if file_type == "bdist_wheel":
wheel_info = wheel_file_re.match(file.name)
if wheel_info is not None:
@@ -211,7 +208,7 @@ def post_data(self, file: "Path") -> Dict[str, Any]:
return data
def _upload(
- self, session: requests.Session, url: str, dry_run: Optional[bool] = False
+ self, session: requests.Session, url: str, dry_run: bool | None = False
) -> None:
for file in self.files:
# TODO: Check existence
@@ -222,8 +219,8 @@ def _upload_file(
self,
session: requests.Session,
url: str,
- file: "Path",
- dry_run: Optional[bool] = False,
+ file: Path,
+ dry_run: bool | None = False,
) -> None:
from cleo.ui.progress_bar import ProgressBar
@@ -236,7 +233,7 @@ def _upload_file(
}
)
- data_to_send: List[Tuple[str, Any]] = self._prepare_data(data)
+ data_to_send: list[tuple[str, Any]] = self._prepare_data(data)
with file.open("rb") as fp:
data_to_send.append(
@@ -318,7 +315,7 @@ def _register(self, session: requests.Session, url: str) -> requests.Response:
return resp
- def _prepare_data(self, data: Dict) -> List[Tuple[str, str]]:
+ def _prepare_data(self, data: dict) -> list[tuple[str, str]]:
data_to_send = []
for key, value in data.items():
if not isinstance(value, (list, tuple)):
@@ -329,7 +326,7 @@ def _prepare_data(self, data: Dict) -> List[Tuple[str, str]]:
return data_to_send
- def _get_type(self, file: "Path") -> str:
+ def _get_type(self, file: Path) -> str:
exts = file.suffixes
if exts[-1] == ".whl":
return "bdist_wheel"
diff --git a/src/poetry/puzzle/__init__.py b/src/poetry/puzzle/__init__.py
index 1b020a047ef..48280ac9bec 100644
--- a/src/poetry/puzzle/__init__.py
+++ b/src/poetry/puzzle/__init__.py
@@ -1 +1,3 @@
+from __future__ import annotations
+
from poetry.puzzle.solver import Solver
diff --git a/src/poetry/puzzle/exceptions.py b/src/poetry/puzzle/exceptions.py
index 92354cc1f89..45d8a7e0a1d 100644
--- a/src/poetry/puzzle/exceptions.py
+++ b/src/poetry/puzzle/exceptions.py
@@ -1,5 +1,4 @@
-from typing import Dict
-from typing import Tuple
+from __future__ import annotations
class SolverProblemError(Exception):
@@ -14,9 +13,9 @@ def error(self) -> Exception:
class OverrideNeeded(Exception):
- def __init__(self, *overrides: Dict) -> None:
+ def __init__(self, *overrides: dict) -> None:
self._overrides = overrides
@property
- def overrides(self) -> Tuple[Dict, ...]:
+ def overrides(self) -> tuple[dict, ...]:
return self._overrides
diff --git a/src/poetry/puzzle/provider.py b/src/poetry/puzzle/provider.py
index ffeb820f56f..055cdb2e010 100644
--- a/src/poetry/puzzle/provider.py
+++ b/src/poetry/puzzle/provider.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import logging
import os
import re
@@ -10,12 +12,7 @@
from tempfile import mkdtemp
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
from typing import Iterator
-from typing import List
-from typing import Optional
-from typing import Set
-from typing import Union
from cleo.ui.progress_indicator import ProgressIndicator
from poetry.core.packages.utils.utils import get_python_constraint_from_marker
@@ -60,38 +57,38 @@ def _formatter_elapsed(self) -> str:
class Provider:
- UNSAFE_PACKAGES: Set[str] = set()
+ UNSAFE_PACKAGES: set[str] = set()
def __init__(
- self, package: "Package", pool: "Pool", io: Any, env: Optional["Env"] = None
+ self, package: Package, pool: Pool, io: Any, env: Env | None = None
) -> None:
self._package = package
self._pool = pool
self._io = io
self._env = env
self._python_constraint = package.python_constraint
- self._search_for: Dict["Dependency", List["Package"]] = {}
+ self._search_for: dict[Dependency, list[Package]] = {}
self._is_debugging = self._io.is_debug() or self._io.is_very_verbose()
self._in_progress = False
- self._overrides: Dict = {}
- self._deferred_cache: Dict["Dependency", "Package"] = {}
+ self._overrides: dict = {}
+ self._deferred_cache: dict[Dependency, Package] = {}
self._load_deferred = True
@property
- def pool(self) -> "Pool":
+ def pool(self) -> Pool:
return self._pool
def is_debugging(self) -> bool:
return self._is_debugging
- def set_overrides(self, overrides: Dict) -> None:
+ def set_overrides(self, overrides: dict) -> None:
self._overrides = overrides
def load_deferred(self, load_deferred: bool) -> None:
self._load_deferred = load_deferred
@contextmanager
- def use_environment(self, env: "Env") -> Iterator["Provider"]:
+ def use_environment(self, env: Env) -> Iterator[Provider]:
original_env = self._env
original_python_constraint = self._python_constraint
@@ -105,14 +102,14 @@ def use_environment(self, env: "Env") -> Iterator["Provider"]:
def search_for(
self,
- dependency: Union[
- "Dependency",
- "VCSDependency",
- "FileDependency",
- "DirectoryDependency",
- "URLDependency",
- ],
- ) -> List["DependencyPackage"]:
+ dependency: (
+ Dependency
+ | VCSDependency
+ | FileDependency
+ | DirectoryDependency
+ | URLDependency
+ ),
+ ) -> list[DependencyPackage]:
"""
Search for the specifications that match the given dependency.
@@ -167,7 +164,7 @@ def search_for(
return PackageCollection(dependency, packages)
- def search_for_vcs(self, dependency: "VCSDependency") -> List["Package"]:
+ def search_for_vcs(self, dependency: VCSDependency) -> list[Package]:
"""
Search for the specifications that match the given VCS dependency.
@@ -208,11 +205,11 @@ def get_package_from_vcs(
cls,
vcs: str,
url: str,
- branch: Optional[str] = None,
- tag: Optional[str] = None,
- rev: Optional[str] = None,
- name: Optional[str] = None,
- ) -> "Package":
+ branch: str | None = None,
+ tag: str | None = None,
+ rev: str | None = None,
+ name: str | None = None,
+ ) -> Package:
if vcs != "git":
raise ValueError(f"Unsupported VCS dependency {vcs}")
@@ -242,7 +239,7 @@ def get_package_from_vcs(
return package
- def search_for_file(self, dependency: "FileDependency") -> List["Package"]:
+ def search_for_file(self, dependency: FileDependency) -> list[Package]:
if dependency in self._deferred_cache:
dependency, _package = self._deferred_cache[dependency]
@@ -272,7 +269,7 @@ def search_for_file(self, dependency: "FileDependency") -> List["Package"]:
return [package]
@classmethod
- def get_package_from_file(cls, file_path: Path) -> "Package":
+ def get_package_from_file(cls, file_path: Path) -> Package:
try:
package = PackageInfo.from_path(path=file_path).to_package(
root_dir=file_path
@@ -284,9 +281,7 @@ def get_package_from_file(cls, file_path: Path) -> "Package":
return package
- def search_for_directory(
- self, dependency: "DirectoryDependency"
- ) -> List["Package"]:
+ def search_for_directory(self, dependency: DirectoryDependency) -> list[Package]:
if dependency in self._deferred_cache:
dependency, _package = self._deferred_cache[dependency]
@@ -310,8 +305,8 @@ def search_for_directory(
@classmethod
def get_package_from_directory(
- cls, directory: Path, name: Optional[str] = None
- ) -> "Package":
+ cls, directory: Path, name: str | None = None
+ ) -> Package:
package = PackageInfo.from_directory(path=directory).to_package(
root_dir=directory
)
@@ -325,7 +320,7 @@ def get_package_from_directory(
return package
- def search_for_url(self, dependency: "URLDependency") -> List["Package"]:
+ def search_for_url(self, dependency: URLDependency) -> list[Package]:
if dependency in self._deferred_cache:
return [self._deferred_cache[dependency]]
@@ -354,7 +349,7 @@ def search_for_url(self, dependency: "URLDependency") -> List["Package"]:
return [package]
@classmethod
- def get_package_from_url(cls, url: str) -> "Package":
+ def get_package_from_url(cls, url: str) -> Package:
file_name = os.path.basename(urllib.parse.urlparse(url).path)
with tempfile.TemporaryDirectory() as temp_dir:
dest = Path(temp_dir) / file_name
@@ -368,7 +363,7 @@ def get_package_from_url(cls, url: str) -> "Package":
def incompatibilities_for(
self, package: DependencyPackage
- ) -> List[Incompatibility]:
+ ) -> list[Incompatibility]:
"""
Returns incompatibilities that encapsulate a given package's dependencies,
or that it can't be safely selected.
@@ -548,7 +543,7 @@ def complete_package(self, package: DependencyPackage) -> DependencyPackage:
# An example of this is:
# - pypiwin32 (220); sys_platform == "win32" and python_version >= "3.6"
# - pypiwin32 (219); sys_platform == "win32" and python_version < "3.6"
- duplicates: Dict[str, List["Dependency"]] = {}
+ duplicates: dict[str, list[Dependency]] = {}
for dep in dependencies:
if dep.complete_name not in duplicates:
duplicates[dep.complete_name] = []
@@ -564,7 +559,7 @@ def complete_package(self, package: DependencyPackage) -> DependencyPackage:
self.debug(f"Duplicate dependencies for {dep_name}")
# Regrouping by constraint
- by_constraint: Dict[str, List["Dependency"]] = {}
+ by_constraint: dict[str, list[Dependency]] = {}
for dep in deps:
if dep.constraint not in by_constraint:
by_constraint[dep.constraint] = []
@@ -631,7 +626,7 @@ def complete_package(self, package: DependencyPackage) -> DependencyPackage:
# - {}
_deps = [_dep[0] for _dep in by_constraint.values()]
- def fmt_warning(d: "Dependency") -> str:
+ def fmt_warning(d: Dependency) -> str:
marker = d.marker if not d.marker.is_any() else "*"
return (
f"{d.name} ({d.pretty_constraint})>"
diff --git a/src/poetry/puzzle/solver.py b/src/poetry/puzzle/solver.py
index 80e32d43b48..32bd327a7be 100644
--- a/src/poetry/puzzle/solver.py
+++ b/src/poetry/puzzle/solver.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import enum
import time
@@ -5,13 +7,9 @@
from contextlib import contextmanager
from typing import TYPE_CHECKING
from typing import Callable
-from typing import Dict
from typing import FrozenSet
from typing import Iterator
-from typing import List
-from typing import Optional
from typing import Tuple
-from typing import Union
from poetry.mixology import resolve_version
from poetry.mixology.failure import SolveFailure
@@ -40,12 +38,12 @@
class Solver:
def __init__(
self,
- package: "ProjectPackage",
- pool: "Pool",
- installed: "Repository",
- locked: "Repository",
- io: "IO",
- provider: Optional[Provider] = None,
+ package: ProjectPackage,
+ pool: Pool,
+ installed: Repository,
+ locked: Repository,
+ io: IO,
+ provider: Provider | None = None,
):
self._package = package
self._pool = pool
@@ -57,18 +55,18 @@ def __init__(
provider = Provider(self._package, self._pool, self._io)
self._provider = provider
- self._overrides: List[Dict] = []
+ self._overrides: list[dict] = []
@property
def provider(self) -> Provider:
return self._provider
@contextmanager
- def use_environment(self, env: "Env") -> Iterator[None]:
+ def use_environment(self, env: Env) -> Iterator[None]:
with self.provider.use_environment(env):
yield
- def solve(self, use_latest: List[str] = None) -> "Transaction":
+ def solve(self, use_latest: list[str] = None) -> Transaction:
from poetry.puzzle.transaction import Transaction
with self._provider.progress():
@@ -94,8 +92,8 @@ def solve(self, use_latest: List[str] = None) -> "Transaction":
)
def solve_in_compatibility_mode(
- self, overrides: Tuple[Dict, ...], use_latest: List[str] = None
- ) -> Tuple[List["Package"], List[int]]:
+ self, overrides: tuple[dict, ...], use_latest: list[str] = None
+ ) -> tuple[list[Package], list[int]]:
packages = []
depths = []
@@ -122,7 +120,7 @@ def solve_in_compatibility_mode(
return packages, depths
- def _solve(self, use_latest: List[str] = None) -> Tuple[List["Package"], List[int]]:
+ def _solve(self, use_latest: list[str] = None) -> tuple[list[Package], list[int]]:
if self._provider._overrides:
self._overrides.append(self._provider._overrides)
@@ -186,10 +184,10 @@ def __init__(self, id: DFSNodeID, name: str, base_name: str) -> None:
self.name = name
self.base_name = base_name
- def reachable(self) -> List:
+ def reachable(self) -> list:
return []
- def visit(self, parents: List["PackageNode"]) -> None:
+ def visit(self, parents: list[PackageNode]) -> None:
pass
def __str__(self) -> str:
@@ -203,11 +201,11 @@ class VisitedState(enum.Enum):
def depth_first_search(
- source: "PackageNode", aggregator: Callable
-) -> List[Tuple["Package", int]]:
- back_edges: Dict[DFSNodeID, List["PackageNode"]] = defaultdict(list)
- visited: Dict[DFSNodeID, VisitedState] = {}
- topo_sorted_nodes: List["PackageNode"] = []
+ source: PackageNode, aggregator: Callable
+) -> list[tuple[Package, int]]:
+ back_edges: dict[DFSNodeID, list[PackageNode]] = defaultdict(list)
+ visited: dict[DFSNodeID, VisitedState] = {}
+ topo_sorted_nodes: list[PackageNode] = []
dfs_visit(source, back_edges, visited, topo_sorted_nodes)
@@ -232,10 +230,10 @@ def depth_first_search(
def dfs_visit(
- node: "PackageNode",
- back_edges: Dict[DFSNodeID, List["PackageNode"]],
- visited: Dict[DFSNodeID, VisitedState],
- sorted_nodes: List["PackageNode"],
+ node: PackageNode,
+ back_edges: dict[DFSNodeID, list[PackageNode]],
+ visited: dict[DFSNodeID, VisitedState],
+ sorted_nodes: list[PackageNode],
) -> bool:
if visited.get(node.id, VisitedState.Unvisited) == VisitedState.Visited:
return True
@@ -258,28 +256,26 @@ def dfs_visit(
class PackageNode(DFSNode):
def __init__(
self,
- package: "Package",
- packages: List["Package"],
- seen: List["Package"],
- previous: Optional["PackageNode"] = None,
- previous_dep: Optional[
- Union[
- "DirectoryDependency",
- "FileDependency",
- "URLDependency",
- "VCSDependency",
- "Dependency",
- ]
- ] = None,
- dep: Optional[
- Union[
- "DirectoryDependency",
- "FileDependency",
- "URLDependency",
- "VCSDependency",
- "Dependency",
- ]
- ] = None,
+ package: Package,
+ packages: list[Package],
+ seen: list[Package],
+ previous: PackageNode | None = None,
+ previous_dep: None
+ | (
+ DirectoryDependency
+ | FileDependency
+ | URLDependency
+ | VCSDependency
+ | Dependency
+ ) = None,
+ dep: None
+ | (
+ DirectoryDependency
+ | FileDependency
+ | URLDependency
+ | VCSDependency
+ | Dependency
+ ) = None,
) -> None:
self.package = package
self.packages = packages
@@ -292,7 +288,7 @@ def __init__(
if not previous:
self.category = "dev"
- self.groups: FrozenSet[str] = frozenset()
+ self.groups: frozenset[str] = frozenset()
self.optional = True
elif dep:
self.category = "main" if "default" in dep.groups else "dev"
@@ -307,8 +303,8 @@ def __init__(
package.name,
)
- def reachable(self) -> List["PackageNode"]:
- children: List[PackageNode] = []
+ def reachable(self) -> list[PackageNode]:
+ children: list[PackageNode] = []
# skip already traversed packages
if self.package in self.seen:
@@ -361,7 +357,7 @@ def reachable(self) -> List["PackageNode"]:
return children
- def visit(self, parents: List["PackageNode"]) -> None:
+ def visit(self, parents: list[PackageNode]) -> None:
# The root package, which has no parents, is defined as having depth -1
# So that the root package's top-level dependencies have depth 0.
self.depth = 1 + max(
@@ -374,11 +370,11 @@ def visit(self, parents: List["PackageNode"]) -> None:
def aggregate_package_nodes(
- nodes: List[PackageNode], children: List[PackageNode]
-) -> Tuple["Package", int]:
+ nodes: list[PackageNode], children: list[PackageNode]
+) -> tuple[Package, int]:
package = nodes[0].package
depth = max(node.depth for node in nodes)
- groups: List[str] = []
+ groups: list[str] = []
for node in nodes:
groups.extend(node.groups)
diff --git a/src/poetry/puzzle/transaction.py b/src/poetry/puzzle/transaction.py
index 858ac2b862e..e54fd964b08 100644
--- a/src/poetry/puzzle/transaction.py
+++ b/src/poetry/puzzle/transaction.py
@@ -1,7 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
-from typing import Tuple
if TYPE_CHECKING:
@@ -13,10 +12,10 @@
class Transaction:
def __init__(
self,
- current_packages: List["Package"],
- result_packages: List[Tuple["Package", int]],
- installed_packages: Optional[List["Package"]] = None,
- root_package: Optional["Package"] = None,
+ current_packages: list[Package],
+ result_packages: list[tuple[Package, int]],
+ installed_packages: list[Package] | None = None,
+ root_package: Package | None = None,
) -> None:
self._current_packages = current_packages
self._result_packages = result_packages
@@ -29,12 +28,12 @@ def __init__(
def calculate_operations(
self, with_uninstalls: bool = True, synchronize: bool = False
- ) -> List["OperationTypes"]:
+ ) -> list[OperationTypes]:
from poetry.installation.operations.install import Install
from poetry.installation.operations.uninstall import Uninstall
from poetry.installation.operations.update import Update
- operations: List["OperationTypes"] = []
+ operations: list[OperationTypes] = []
for result_package, priority in self._result_packages:
installed = False
diff --git a/src/poetry/repositories/__init__.py b/src/poetry/repositories/__init__.py
index 67fa6946c14..af0d42a9e4a 100644
--- a/src/poetry/repositories/__init__.py
+++ b/src/poetry/repositories/__init__.py
@@ -1,2 +1,4 @@
+from __future__ import annotations
+
from poetry.repositories.pool import Pool
from poetry.repositories.repository import Repository
diff --git a/src/poetry/repositories/base_repository.py b/src/poetry/repositories/base_repository.py
index 4aa77fcb2a6..53207ded1b0 100644
--- a/src/poetry/repositories/base_repository.py
+++ b/src/poetry/repositories/base_repository.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
if TYPE_CHECKING:
@@ -10,22 +10,22 @@
class BaseRepository:
def __init__(self) -> None:
- self._packages: List["Package"] = []
+ self._packages: list[Package] = []
@property
- def packages(self) -> List["Package"]:
+ def packages(self) -> list[Package]:
return self._packages
- def has_package(self, package: "Package") -> bool:
+ def has_package(self, package: Package) -> bool:
raise NotImplementedError()
def package(
- self, name: str, version: str, extras: Optional[List[str]] = None
- ) -> "Package":
+ self, name: str, version: str, extras: list[str] | None = None
+ ) -> Package:
raise NotImplementedError()
- def find_packages(self, dependency: "Dependency") -> List["Package"]:
+ def find_packages(self, dependency: Dependency) -> list[Package]:
raise NotImplementedError()
- def search(self, query: str) -> List["Package"]:
+ def search(self, query: str) -> list[Package]:
raise NotImplementedError()
diff --git a/src/poetry/repositories/exceptions.py b/src/poetry/repositories/exceptions.py
index 170303f3945..db0ad8edd9f 100644
--- a/src/poetry/repositories/exceptions.py
+++ b/src/poetry/repositories/exceptions.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+
class RepositoryError(Exception):
pass
diff --git a/src/poetry/repositories/installed_repository.py b/src/poetry/repositories/installed_repository.py
index b4c9f848bbc..47130090f40 100644
--- a/src/poetry/repositories/installed_repository.py
+++ b/src/poetry/repositories/installed_repository.py
@@ -1,11 +1,10 @@
+from __future__ import annotations
+
import itertools
import json
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Set
-from typing import Tuple
-from typing import Union
from poetry.core.packages.package import Package
from poetry.core.packages.utils.utils import url_to_path
@@ -31,7 +30,7 @@
class InstalledRepository(Repository):
@classmethod
- def get_package_paths(cls, env: "Env", name: str) -> Set[Path]:
+ def get_package_paths(cls, env: Env, name: str) -> set[Path]:
"""
Process a .pth file within the site-packages directories, and return any valid
paths. We skip executable .pth files as there is no reliable means to do this
@@ -77,7 +76,7 @@ def get_package_paths(cls, env: "Env", name: str) -> Set[Path]:
return paths
@classmethod
- def get_package_vcs_properties_from_path(cls, src: Path) -> Tuple[str, str, str]:
+ def get_package_vcs_properties_from_path(cls, src: Path) -> tuple[str, str, str]:
from poetry.core.vcs.git import Git
git = Git()
@@ -87,7 +86,7 @@ def get_package_vcs_properties_from_path(cls, src: Path) -> Tuple[str, str, str]
return "git", url, revision
@classmethod
- def is_vcs_package(cls, package: Union[Path, Package], env: "Env") -> bool:
+ def is_vcs_package(cls, package: Path | Package, env: Env) -> bool:
# A VCS dependency should have been installed
# in the src directory.
src = env.path / "src"
@@ -103,7 +102,7 @@ def is_vcs_package(cls, package: Union[Path, Package], env: "Env") -> bool:
@classmethod
def create_package_from_distribution(
- cls, distribution: metadata.Distribution, env: "Env"
+ cls, distribution: metadata.Distribution, env: Env
) -> Package:
# We first check for a direct_url.json file to determine
# the type of package.
@@ -220,7 +219,7 @@ def create_package_from_pep610(cls, distribution: metadata.Distribution) -> Pack
return package
@classmethod
- def load(cls, env: "Env", with_dependencies: bool = False) -> "InstalledRepository":
+ def load(cls, env: Env, with_dependencies: bool = False) -> InstalledRepository:
"""
Load installed packages.
"""
diff --git a/src/poetry/repositories/legacy_repository.py b/src/poetry/repositories/legacy_repository.py
index 23c9223d323..5a48fa4b585 100644
--- a/src/poetry/repositories/legacy_repository.py
+++ b/src/poetry/repositories/legacy_repository.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import cgi
import hashlib
import re
@@ -9,10 +11,7 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
from typing import Iterator
-from typing import List
-from typing import Optional
from urllib.parse import quote
import requests.auth
@@ -62,7 +61,7 @@ class Page:
".tar",
]
- def __init__(self, url: str, content: str, headers: Dict[str, Any]) -> None:
+ def __init__(self, url: str, content: str, headers: dict[str, Any]) -> None:
if not url.endswith("/"):
url += "/"
@@ -120,7 +119,7 @@ def links_for_version(self, version: Version) -> Iterator[Link]:
if self.link_version(link) == version:
yield link
- def link_version(self, link: Link) -> Optional[Version]:
+ def link_version(self, link: Link) -> Version | None:
m = wheel_file_re.match(link.filename)
if m:
version = m.group("ver")
@@ -155,10 +154,10 @@ def __init__(
self,
name: str,
url: str,
- config: Optional[Config] = None,
+ config: Config | None = None,
disable_cache: bool = False,
- cert: Optional[Path] = None,
- client_cert: Optional[Path] = None,
+ cert: Path | None = None,
+ client_cert: Path | None = None,
) -> None:
if name == "pypi":
raise ValueError("The name [pypi] is reserved for repositories")
@@ -204,11 +203,11 @@ def __init__(
self._disable_cache = disable_cache
@property
- def cert(self) -> Optional[Path]:
+ def cert(self) -> Path | None:
return self._cert
@property
- def client_cert(self) -> Optional[Path]:
+ def client_cert(self) -> Path | None:
return self._client_cert
@property
@@ -222,7 +221,7 @@ def authenticated_url(self) -> str:
return f"{parsed.scheme}://{username}:{password}@{parsed.netloc}{parsed.path}"
- def find_packages(self, dependency: "Dependency") -> List[Package]:
+ def find_packages(self, dependency: Dependency) -> list[Package]:
packages = []
constraint = dependency.constraint
@@ -291,7 +290,7 @@ def find_packages(self, dependency: "Dependency") -> List[Package]:
return packages
def package(
- self, name: str, version: str, extras: Optional[List[str]] = None
+ self, name: str, version: str, extras: list[str] | None = None
) -> Package:
"""
Retrieve the release information.
@@ -316,7 +315,7 @@ def package(
return package
- def find_links_for_package(self, package: Package) -> List[Link]:
+ def find_links_for_package(self, package: Package) -> list[Link]:
page = self._get_page(f"/{package.name.replace('.', '-')}/")
if page is None:
return []
@@ -395,7 +394,7 @@ def _get_release_info(self, name: str, version: str) -> dict:
return data.asdict()
- def _get_page(self, endpoint: str) -> Optional[Page]:
+ def _get_page(self, endpoint: str) -> Page | None:
url = self._url + endpoint
try:
response = self.session.get(url)
diff --git a/src/poetry/repositories/pool.py b/src/poetry/repositories/pool.py
index 6ff2d4857bf..bca3a4296d7 100644
--- a/src/poetry/repositories/pool.py
+++ b/src/poetry/repositories/pool.py
@@ -1,8 +1,7 @@
+from __future__ import annotations
+
from contextlib import suppress
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
-from typing import Optional
from poetry.repositories.base_repository import BaseRepository
from poetry.repositories.exceptions import PackageNotFound
@@ -18,17 +17,17 @@
class Pool(BaseRepository):
def __init__(
self,
- repositories: Optional[List["Repository"]] = None,
+ repositories: list[Repository] | None = None,
ignore_repository_names: bool = False,
) -> None:
if repositories is None:
repositories = []
- self._lookup: Dict[Optional[str], int] = {}
- self._repositories: List["Repository"] = []
+ self._lookup: dict[str | None, int] = {}
+ self._repositories: list[Repository] = []
self._default = False
self._has_primary_repositories = False
- self._secondary_start_idx: Optional[int] = None
+ self._secondary_start_idx: int | None = None
for repository in repositories:
self.add_repository(repository)
@@ -38,7 +37,7 @@ def __init__(
super().__init__()
@property
- def repositories(self) -> List["Repository"]:
+ def repositories(self) -> list[Repository]:
return self._repositories
def has_default(self) -> bool:
@@ -52,7 +51,7 @@ def has_repository(self, name: str) -> bool:
return name in self._lookup
- def repository(self, name: str) -> "Repository":
+ def repository(self, name: str) -> Repository:
if name is not None:
name = name.lower()
@@ -62,8 +61,8 @@ def repository(self, name: str) -> "Repository":
raise ValueError(f'Repository "{name}" does not exist.')
def add_repository(
- self, repository: "Repository", default: bool = False, secondary: bool = False
- ) -> "Pool":
+ self, repository: Repository, default: bool = False, secondary: bool = False
+ ) -> Pool:
"""
Adds a repository to the pool.
"""
@@ -110,7 +109,7 @@ def add_repository(
return self
- def remove_repository(self, repository_name: str) -> "Pool":
+ def remove_repository(self, repository_name: str) -> Pool:
if repository_name is not None:
repository_name = repository_name.lower()
@@ -120,12 +119,12 @@ def remove_repository(self, repository_name: str) -> "Pool":
return self
- def has_package(self, package: "Package") -> bool:
+ def has_package(self, package: Package) -> bool:
raise NotImplementedError()
def package(
- self, name: str, version: str, extras: List[str] = None, repository: str = None
- ) -> "Package":
+ self, name: str, version: str, extras: list[str] = None, repository: str = None
+ ) -> Package:
if repository is not None:
repository = repository.lower()
@@ -153,7 +152,7 @@ def package(
raise PackageNotFound(f"Package {name} ({version}) not found.")
- def find_packages(self, dependency: "Dependency") -> List["Package"]:
+ def find_packages(self, dependency: Dependency) -> list[Package]:
repository = dependency.source_name
if repository is not None:
repository = repository.lower()
@@ -174,7 +173,7 @@ def find_packages(self, dependency: "Dependency") -> List["Package"]:
return packages
- def search(self, query: str) -> List["Package"]:
+ def search(self, query: str) -> list[Package]:
from poetry.repositories.legacy_repository import LegacyRepository
results = []
diff --git a/src/poetry/repositories/pypi_repository.py b/src/poetry/repositories/pypi_repository.py
index 6caf68234ab..467a5a9c8cb 100644
--- a/src/poetry/repositories/pypi_repository.py
+++ b/src/poetry/repositories/pypi_repository.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import logging
import os
import urllib.parse
@@ -5,9 +7,6 @@
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
-from typing import Union
import requests
@@ -85,7 +84,7 @@ def session(self) -> CacheControl:
def __del__(self) -> None:
self._session.close()
- def find_packages(self, dependency: Dependency) -> List[Package]:
+ def find_packages(self, dependency: Dependency) -> list[Package]:
"""
Find packages on the remote server.
"""
@@ -157,11 +156,11 @@ def package(
self,
name: str,
version: str,
- extras: (Union[list, None]) = None,
+ extras: (list | None) = None,
) -> Package:
return self.get_release_info(name, version).to_package(name=name, extras=extras)
- def search(self, query: str) -> List[Package]:
+ def search(self, query: str) -> list[Package]:
results = []
search = {"q": query}
@@ -213,7 +212,7 @@ def _get_package_info(self, name: str) -> dict:
return data
- def get_release_info(self, name: str, version: str) -> "PackageInfo":
+ def get_release_info(self, name: str, version: str) -> PackageInfo:
"""
Return the release information given a package name and a version.
@@ -242,7 +241,7 @@ def get_release_info(self, name: str, version: str) -> "PackageInfo":
return PackageInfo.load(cached)
- def find_links_for_package(self, package: Package) -> List[Link]:
+ def find_links_for_package(self, package: Package) -> list[Link]:
json_data = self._get(f"pypi/{package.name}/{package.version}/json")
if json_data is None:
return []
@@ -317,7 +316,7 @@ def _get_release_info(self, name: str, version: str) -> dict:
return data.asdict()
- def _get(self, endpoint: str) -> Union[dict, None]:
+ def _get(self, endpoint: str) -> dict | None:
try:
json_response = self.session.get(self._base_url + endpoint)
except requests.exceptions.TooManyRedirects:
@@ -331,7 +330,7 @@ def _get(self, endpoint: str) -> Union[dict, None]:
return json_response.json()
- def _get_info_from_urls(self, urls: Dict[str, List[str]]) -> "PackageInfo":
+ def _get_info_from_urls(self, urls: dict[str, list[str]]) -> PackageInfo:
# Checking wheels first as they are more likely to hold
# the necessary information
if "bdist_wheel" in urls:
@@ -423,7 +422,7 @@ def _get_info_from_urls(self, urls: Dict[str, List[str]]) -> "PackageInfo":
return self._get_info_from_sdist(urls["sdist"][0])
- def _get_info_from_wheel(self, url: str) -> "PackageInfo":
+ def _get_info_from_wheel(self, url: str) -> PackageInfo:
from poetry.inspection.info import PackageInfo
wheel_name = urllib.parse.urlparse(url).path.rsplit("/")[-1]
@@ -436,7 +435,7 @@ def _get_info_from_wheel(self, url: str) -> "PackageInfo":
return PackageInfo.from_wheel(filepath)
- def _get_info_from_sdist(self, url: str) -> "PackageInfo":
+ def _get_info_from_sdist(self, url: str) -> PackageInfo:
from poetry.inspection.info import PackageInfo
sdist_name = urllib.parse.urlparse(url).path
diff --git a/src/poetry/repositories/remote_repository.py b/src/poetry/repositories/remote_repository.py
index e92a4eb6d2d..64f90dead90 100644
--- a/src/poetry/repositories/remote_repository.py
+++ b/src/poetry/repositories/remote_repository.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.repositories.repository import Repository
diff --git a/src/poetry/repositories/repository.py b/src/poetry/repositories/repository.py
index 086c91a0f41..4b41373f68c 100644
--- a/src/poetry/repositories/repository.py
+++ b/src/poetry/repositories/repository.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
from poetry.repositories.base_repository import BaseRepository
@@ -12,7 +12,7 @@
class Repository(BaseRepository):
- def __init__(self, packages: List["Package"] = None, name: str = None) -> None:
+ def __init__(self, packages: list[Package] = None, name: str = None) -> None:
super().__init__()
self._name = name
@@ -24,19 +24,19 @@ def __init__(self, packages: List["Package"] = None, name: str = None) -> None:
self.add_package(package)
@property
- def name(self) -> Optional[str]:
+ def name(self) -> str | None:
return self._name
def package(
- self, name: str, version: str, extras: Optional[List[str]] = None
- ) -> "Package":
+ self, name: str, version: str, extras: list[str] | None = None
+ ) -> Package:
name = name.lower()
for package in self.packages:
if name == package.name and package.version.text == version:
return package.clone()
- def find_packages(self, dependency: "Dependency") -> List["Package"]:
+ def find_packages(self, dependency: Dependency) -> list[Package]:
from poetry.core.semver.helpers import parse_constraint
from poetry.core.semver.version_constraint import VersionConstraint
from poetry.core.semver.version_range import VersionRange
@@ -82,16 +82,16 @@ def find_packages(self, dependency: "Dependency") -> List["Package"]:
return packages or ignored_pre_release_packages
- def has_package(self, package: "Package") -> bool:
+ def has_package(self, package: Package) -> bool:
package_id = package.unique_name
return any(
package_id == repo_package.unique_name for repo_package in self.packages
)
- def add_package(self, package: "Package") -> None:
+ def add_package(self, package: Package) -> None:
self._packages.append(package)
- def remove_package(self, package: "Package") -> None:
+ def remove_package(self, package: Package) -> None:
package_id = package.unique_name
index = None
@@ -103,11 +103,11 @@ def remove_package(self, package: "Package") -> None:
if index is not None:
del self._packages[index]
- def find_links_for_package(self, package: "Package") -> List["Link"]:
+ def find_links_for_package(self, package: Package) -> list[Link]:
return []
- def search(self, query: str) -> List["Package"]:
- results: List["Package"] = []
+ def search(self, query: str) -> list[Package]:
+ results: list[Package] = []
for package in self.packages:
if query in package.name:
diff --git a/src/poetry/utils/_compat.py b/src/poetry/utils/_compat.py
index d3affb342f6..fe0ef434d19 100644
--- a/src/poetry/utils/_compat.py
+++ b/src/poetry/utils/_compat.py
@@ -1,8 +1,8 @@
+from __future__ import annotations
+
import sys
from contextlib import suppress
-from typing import List
-from typing import Optional
if sys.version_info < (3, 8):
@@ -14,7 +14,7 @@
WINDOWS = sys.platform == "win32"
-def decode(string: str, encodings: Optional[List[str]] = None) -> str:
+def decode(string: str, encodings: list[str] | None = None) -> str:
if not isinstance(string, bytes):
return string
@@ -27,7 +27,7 @@ def decode(string: str, encodings: Optional[List[str]] = None) -> str:
return string.decode(encodings[0], errors="ignore")
-def encode(string: str, encodings: Optional[List[str]] = None) -> bytes:
+def encode(string: str, encodings: list[str] | None = None) -> bytes:
if isinstance(string, bytes):
return string
@@ -44,7 +44,7 @@ def to_str(string: str) -> str:
return decode(string)
-def list_to_shell_command(cmd: List[str]) -> str:
+def list_to_shell_command(cmd: list[str]) -> str:
return " ".join(
f'"{token}"' if " " in token and token[0] not in {"'", '"'} else token
for token in cmd
diff --git a/src/poetry/utils/appdirs.py b/src/poetry/utils/appdirs.py
index 0b0bdda4d0b..ca6bb9a432d 100644
--- a/src/poetry/utils/appdirs.py
+++ b/src/poetry/utils/appdirs.py
@@ -2,12 +2,12 @@
This code was taken from https://github.com/ActiveState/appdirs and modified
to suit our purposes.
"""
+from __future__ import annotations
+
import os
import sys
from typing import TYPE_CHECKING
-from typing import List
-from typing import Union
if TYPE_CHECKING:
@@ -17,7 +17,7 @@
WINDOWS = sys.platform.startswith("win") or (sys.platform == "cli" and os.name == "nt")
-def expanduser(path: Union[str, "Path"]) -> str:
+def expanduser(path: str | Path) -> str:
"""
Expand ~ and ~user constructions.
@@ -143,7 +143,7 @@ def user_config_dir(appname: str, roaming: bool = True) -> str:
# for the discussion regarding site_config_dirs locations
# see
-def site_config_dirs(appname: str) -> List[str]:
+def site_config_dirs(appname: str) -> list[str]:
r"""Return a list of potential user-shared config dirs for this application.
"appname" is the name of application.
diff --git a/src/poetry/utils/authenticator.py b/src/poetry/utils/authenticator.py
index 9c01461e9fa..a7d0dda3d89 100644
--- a/src/poetry/utils/authenticator.py
+++ b/src/poetry/utils/authenticator.py
@@ -1,12 +1,11 @@
+from __future__ import annotations
+
import logging
import time
import urllib.parse
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import Optional
-from typing import Tuple
import requests
import requests.auth
@@ -26,7 +25,7 @@
class Authenticator:
- def __init__(self, config: "Config", io: Optional["IO"] = None) -> None:
+ def __init__(self, config: Config, io: IO | None = None) -> None:
self._config = config
self._io = io
self._session = None
@@ -100,7 +99,7 @@ def request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
# this should never really be hit under any sane circumstance
raise PoetryException("Failed HTTP {} request", method.upper())
- def get_credentials_for_url(self, url: str) -> Tuple[Optional[str], Optional[str]]:
+ def get_credentials_for_url(self, url: str) -> tuple[str | None, str | None]:
parsed_url = urllib.parse.urlsplit(url)
netloc = parsed_url.netloc
@@ -133,12 +132,10 @@ def get_credentials_for_url(self, url: str) -> Tuple[Optional[str], Optional[str
def get_pypi_token(self, name: str) -> str:
return self._password_manager.get_pypi_token(name)
- def get_http_auth(self, name: str) -> Optional[Dict[str, str]]:
+ def get_http_auth(self, name: str) -> dict[str, str] | None:
return self._get_http_auth(name, None)
- def _get_http_auth(
- self, name: str, netloc: Optional[str]
- ) -> Optional[Dict[str, str]]:
+ def _get_http_auth(self, name: str, netloc: str | None) -> dict[str, str] | None:
if name == "pypi":
url = "https://upload.pypi.org/legacy/"
else:
@@ -159,9 +156,7 @@ def _get_http_auth(
return auth
- def _get_credentials_for_netloc(
- self, netloc: str
- ) -> Tuple[Optional[str], Optional[str]]:
+ def _get_credentials_for_netloc(self, netloc: str) -> tuple[str | None, str | None]:
for repository_name in self._config.get("repositories", []):
auth = self._get_http_auth(repository_name, netloc)
@@ -173,8 +168,8 @@ def _get_credentials_for_netloc(
return None, None
def _get_credentials_for_netloc_from_keyring(
- self, url: str, netloc: str, username: Optional[str]
- ) -> Optional[Dict[str, str]]:
+ self, url: str, netloc: str, username: str | None
+ ) -> dict[str, str] | None:
import keyring
cred = keyring.get_credential(url, username)
diff --git a/src/poetry/utils/env.py b/src/poetry/utils/env.py
index 7e2218d684e..36f2f0e598a 100644
--- a/src/poetry/utils/env.py
+++ b/src/poetry/utils/env.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import base64
import hashlib
import itertools
@@ -18,13 +20,8 @@
from typing import TYPE_CHECKING
from typing import Any
from typing import ContextManager
-from typing import Dict
from typing import Iterable
from typing import Iterator
-from typing import List
-from typing import Optional
-from typing import Tuple
-from typing import Union
import packaging.tags
import tomlkit
@@ -200,8 +197,8 @@ class SitePackages:
def __init__(
self,
purelib: Path,
- platlib: Optional[Path] = None,
- fallbacks: List[Path] = None,
+ platlib: Path | None = None,
+ fallbacks: list[Path] = None,
skip_write_checks: bool = False,
) -> None:
self._purelib = purelib
@@ -213,7 +210,7 @@ def __init__(
self._fallbacks = fallbacks or []
self._skip_write_checks = skip_write_checks
- self._candidates: List[Path] = []
+ self._candidates: list[Path] = []
for path in itertools.chain([self._purelib, self._platlib], self._fallbacks):
if path not in self._candidates:
self._candidates.append(path)
@@ -233,11 +230,11 @@ def platlib(self) -> Path:
return self._platlib
@property
- def candidates(self) -> List[Path]:
+ def candidates(self) -> list[Path]:
return self._candidates
@property
- def writable_candidates(self) -> List[Path]:
+ def writable_candidates(self) -> list[Path]:
if self._writable_candidates is not None:
return self._writable_candidates
@@ -251,7 +248,7 @@ def writable_candidates(self) -> List[Path]:
def make_candidates(
self, path: Path, writable_only: bool = False, strict: bool = False
- ) -> List[Path]:
+ ) -> list[Path]:
candidates = self._candidates if not writable_only else self.writable_candidates
if path.is_absolute():
for candidate in candidates:
@@ -276,7 +273,7 @@ def make_candidates(
return results
def distributions(
- self, name: Optional[str] = None, writable_only: bool = False
+ self, name: str | None = None, writable_only: bool = False
) -> Iterable[metadata.PathDistribution]:
path = list(
map(
@@ -288,7 +285,7 @@ def distributions(
def find_distribution(
self, name: str, writable_only: bool = False
- ) -> Optional[metadata.PathDistribution]:
+ ) -> metadata.PathDistribution | None:
for distribution in self.distributions(name=name, writable_only=writable_only):
return distribution
return None
@@ -331,7 +328,7 @@ def find_distribution_direct_url_json_files(
writable_only=writable_only,
)
- def remove_distribution_files(self, distribution_name: str) -> List[Path]:
+ def remove_distribution_files(self, distribution_name: str) -> list[Path]:
paths = []
for distribution in self.distributions(
@@ -352,13 +349,13 @@ def remove_distribution_files(self, distribution_name: str) -> List[Path]:
def _path_method_wrapper(
self,
- path: Union[str, Path],
+ path: str | Path,
method: str,
*args: Any,
return_first: bool = True,
writable_only: bool = False,
**kwargs: Any,
- ) -> Union[Tuple[Path, Any], List[Tuple[Path, Any]]]:
+ ) -> tuple[Path, Any] | list[tuple[Path, Any]]:
if isinstance(path, str):
path = Path(path)
@@ -383,13 +380,13 @@ def _path_method_wrapper(
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: str | Path, *args: Any, **kwargs: Any) -> Path:
return self._path_method_wrapper(path, "write_text", *args, **kwargs)[0]
- def mkdir(self, path: Union[str, Path], *args: Any, **kwargs: Any) -> Path:
+ def mkdir(self, path: str | Path, *args: Any, **kwargs: Any) -> Path:
return self._path_method_wrapper(path, "mkdir", *args, **kwargs)[0]
- def exists(self, path: Union[str, Path]) -> bool:
+ def exists(self, path: str | Path) -> bool:
return any(
value[-1]
for value in self._path_method_wrapper(path, "exists", return_first=False)
@@ -397,9 +394,9 @@ def exists(self, path: Union[str, Path]) -> bool:
def find(
self,
- path: Union[str, Path],
+ path: str | Path,
writable_only: bool = False,
- ) -> List[Path]:
+ ) -> list[Path]:
return [
value[0]
for value in self._path_method_wrapper(
@@ -421,7 +418,7 @@ class EnvError(Exception):
class EnvCommandError(EnvError):
- def __init__(self, e: CalledProcessError, input: Optional[str] = None) -> None:
+ def __init__(self, e: CalledProcessError, input: str | None = None) -> None:
self.e = e
message = (
@@ -434,7 +431,7 @@ def __init__(self, e: CalledProcessError, input: Optional[str] = None) -> None:
class NoCompatiblePythonVersionFound(EnvError):
- def __init__(self, expected: str, given: Optional[str] = None) -> None:
+ def __init__(self, expected: str, given: str | None = None) -> None:
if given:
message = (
f"The specified Python version ({given}) "
@@ -462,7 +459,7 @@ class EnvManager:
ENVS_FILE = "envs.toml"
- def __init__(self, poetry: "Poetry") -> None:
+ def __init__(self, poetry: Poetry) -> None:
self._poetry = poetry
def _full_python_path(self, python: str) -> str:
@@ -480,7 +477,7 @@ def _full_python_path(self, python: str) -> str:
return executable
- def _detect_active_python(self, io: "IO") -> str:
+ def _detect_active_python(self, io: IO) -> str:
executable = None
try:
@@ -499,7 +496,7 @@ def _detect_active_python(self, io: "IO") -> str:
)
return executable
- def activate(self, python: str, io: "IO") -> "Env":
+ def activate(self, python: str, io: IO) -> Env:
venv_path = self._poetry.config.get("virtualenvs.path")
if venv_path is None:
venv_path = Path(CACHE_DIR) / "virtualenvs"
@@ -592,7 +589,7 @@ def activate(self, python: str, io: "IO") -> "Env":
return self.get(reload=True)
- def deactivate(self, io: "IO") -> None:
+ def deactivate(self, io: IO) -> None:
venv_path = self._poetry.config.get("virtualenvs.path")
if venv_path is None:
venv_path = Path(CACHE_DIR) / "virtualenvs"
@@ -613,7 +610,7 @@ def deactivate(self, io: "IO") -> None:
envs_file.write(envs)
- def get(self, reload: bool = False) -> Union["VirtualEnv", "SystemEnv"]:
+ def get(self, reload: bool = False) -> VirtualEnv | SystemEnv:
if self._env is not None and not reload:
return self._env
@@ -684,7 +681,7 @@ def get(self, reload: bool = False) -> Union["VirtualEnv", "SystemEnv"]:
return VirtualEnv(prefix, base_prefix)
- def list(self, name: Optional[str] = None) -> List["VirtualEnv"]:
+ def list(self, name: str | None = None) -> list[VirtualEnv]:
if name is None:
name = self._poetry.package.name
@@ -709,7 +706,7 @@ def list(self, name: Optional[str] = None) -> List["VirtualEnv"]:
env_list.insert(0, VirtualEnv(venv))
return env_list
- def remove(self, python: str) -> "Env":
+ def remove(self, python: str) -> Env:
venv_path = self._poetry.config.get("virtualenvs.path")
if venv_path is None:
venv_path = Path(CACHE_DIR) / "virtualenvs"
@@ -796,11 +793,11 @@ def remove(self, python: str) -> "Env":
def create_venv(
self,
- io: "IO",
- name: Optional[str] = None,
- executable: Optional[str] = None,
+ io: IO,
+ name: str | None = None,
+ executable: str | None = None,
force: bool = False,
- ) -> Union["SystemEnv", "VirtualEnv"]:
+ ) -> SystemEnv | VirtualEnv:
if self._env is not None and not force:
return self._env
@@ -980,12 +977,12 @@ def create_venv(
@classmethod
def build_venv(
cls,
- path: Union[Path, str],
- executable: Optional[Union[str, Path]] = None,
- flags: Dict[str, bool] = None,
- with_pip: Optional[bool] = None,
- with_wheel: Optional[bool] = None,
- with_setuptools: Optional[bool] = None,
+ path: Path | str,
+ executable: str | Path | None = None,
+ flags: dict[str, bool] = None,
+ with_pip: bool | None = None,
+ with_wheel: bool | None = None,
+ with_setuptools: bool | None = None,
) -> virtualenv.run.session.Session:
flags = flags or {}
@@ -1026,7 +1023,7 @@ def build_venv(
return virtualenv.cli_run(args)
@classmethod
- def remove_venv(cls, path: Union[Path, str]) -> None:
+ def remove_venv(cls, path: Path | str) -> None:
if isinstance(path, str):
path = Path(path)
assert path.is_dir()
@@ -1049,7 +1046,7 @@ def remove_venv(cls, path: Union[Path, str]) -> None:
shutil.rmtree(str(file_path))
@classmethod
- def get_system_env(cls, naive: bool = False) -> Union["SystemEnv", "GenericEnv"]:
+ def get_system_env(cls, naive: bool = False) -> SystemEnv | GenericEnv:
"""
Retrieve the current Python environment.
@@ -1105,7 +1102,7 @@ class Env:
An abstract Python environment.
"""
- def __init__(self, path: Path, base: Optional[Path] = None) -> None:
+ def __init__(self, path: Path, base: Path | None = None) -> None:
self._is_windows = sys.platform == "win32"
self._is_mingw = sysconfig.get_platform().startswith("mingw")
self._is_conda = bool(os.environ.get("CONDA_DEFAULT_ENV"))
@@ -1144,7 +1141,7 @@ def base(self) -> Path:
return self._base
@property
- def version_info(self) -> Tuple[int]:
+ def version_info(self) -> tuple[int]:
return tuple(self.marker_env["version_info"])
@property
@@ -1159,14 +1156,14 @@ def python(self) -> str:
return self._bin(self._executable)
@property
- def marker_env(self) -> Dict[str, Any]:
+ def marker_env(self) -> dict[str, Any]:
if self._marker_env is None:
self._marker_env = self.get_marker_env()
return self._marker_env
@property
- def parent_env(self) -> "GenericEnv":
+ def parent_env(self) -> GenericEnv:
return GenericEnv(self.base, child_env=self)
def _find_python_executable(self) -> None:
@@ -1256,13 +1253,13 @@ def site_packages(self) -> SitePackages:
return self._site_packages
@property
- def usersite(self) -> Optional[Path]:
+ def usersite(self) -> Path | None:
if "usersite" in self.paths:
return Path(self.paths["usersite"])
return None
@property
- def userbase(self) -> Optional[Path]:
+ def userbase(self) -> Path | None:
if "userbase" in self.paths:
return Path(self.paths["userbase"])
return None
@@ -1295,18 +1292,18 @@ def is_path_relative_to_lib(self, path: Path) -> bool:
return False
@property
- def sys_path(self) -> List[str]:
+ def sys_path(self) -> list[str]:
raise NotImplementedError()
@property
- def paths(self) -> Dict[str, str]:
+ def paths(self) -> dict[str, str]:
if self._paths is None:
self._paths = self.get_paths()
return self._paths
@property
- def supported_tags(self) -> List[Tag]:
+ def supported_tags(self) -> list[Tag]:
if self._supported_tags is None:
self._supported_tags = self.get_supported_tags()
@@ -1322,28 +1319,28 @@ def get_base_prefix(cls) -> Path:
return Path(sys.prefix)
- def get_version_info(self) -> Tuple[int]:
+ def get_version_info(self) -> tuple[int]:
raise NotImplementedError()
def get_python_implementation(self) -> str:
raise NotImplementedError()
- def get_marker_env(self) -> Dict[str, Any]:
+ def get_marker_env(self) -> dict[str, Any]:
raise NotImplementedError()
- def get_pip_command(self, embedded: bool = False) -> List[str]:
+ def get_pip_command(self, embedded: bool = False) -> list[str]:
raise NotImplementedError()
- def get_supported_tags(self) -> List[Tag]:
+ def get_supported_tags(self) -> list[Tag]:
raise NotImplementedError()
def get_pip_version(self) -> Version:
raise NotImplementedError()
- def get_paths(self) -> Dict[str, str]:
+ def get_paths(self) -> dict[str, str]:
raise NotImplementedError()
- def is_valid_for_marker(self, marker: "BaseMarker") -> bool:
+ def is_valid_for_marker(self, marker: BaseMarker) -> bool:
return marker.validate(self.marker_env)
def is_sane(self) -> bool:
@@ -1352,7 +1349,7 @@ def is_sane(self) -> bool:
"""
return True
- def get_command_from_bin(self, bin: str) -> List[str]:
+ def get_command_from_bin(self, bin: str) -> list[str]:
if bin == "pip":
# when pip is required we need to ensure that we fallback to
# embedded pip when pip is not available in the environment
@@ -1360,19 +1357,19 @@ def get_command_from_bin(self, bin: str) -> List[str]:
return [self._bin(bin)]
- def run(self, bin: str, *args: str, **kwargs: Any) -> Union[str, int]:
+ def run(self, bin: str, *args: str, **kwargs: Any) -> str | int:
cmd = self.get_command_from_bin(bin) + list(args)
return self._run(cmd, **kwargs)
- def run_pip(self, *args: str, **kwargs: Any) -> Union[int, str]:
+ def run_pip(self, *args: str, **kwargs: Any) -> int | str:
pip = self.get_pip_command(embedded=True)
cmd = pip + list(args)
return self._run(cmd, **kwargs)
- def run_python_script(self, content: str, **kwargs: Any) -> Union[int, str]:
+ def run_python_script(self, content: str, **kwargs: Any) -> int | str:
return self.run(self._executable, "-W", "ignore", "-", input_=content, **kwargs)
- def _run(self, cmd: List[str], **kwargs: Any) -> Union[int, str]:
+ def _run(self, cmd: list[str], **kwargs: Any) -> int | str:
"""
Run a command inside the Python environment.
"""
@@ -1407,7 +1404,7 @@ def _run(self, cmd: List[str], **kwargs: Any) -> Union[int, str]:
return decode(output)
- def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
+ def execute(self, bin: str, *args: str, **kwargs: Any) -> int | None:
command = self.get_command_from_bin(bin) + list(args)
env = kwargs.pop("env", dict(os.environ))
@@ -1422,7 +1419,7 @@ def is_venv(self) -> bool:
raise NotImplementedError()
@property
- def script_dirs(self) -> List[Path]:
+ def script_dirs(self) -> list[Path]:
if self._script_dirs is None:
self._script_dirs = (
[Path(self.paths["scripts"])]
@@ -1477,21 +1474,21 @@ def python(self) -> str:
return sys.executable
@property
- def sys_path(self) -> List[str]:
+ def sys_path(self) -> list[str]:
return sys.path
- def get_version_info(self) -> Tuple[int]:
+ def get_version_info(self) -> tuple[int]:
return sys.version_info
def get_python_implementation(self) -> str:
return platform.python_implementation()
- def get_pip_command(self, embedded: bool = False) -> List[str]:
+ def get_pip_command(self, embedded: bool = False) -> list[str]:
# If we're not in a venv, assume the interpreter we're running on
# has a pip and use that
return [sys.executable, self.pip_embedded if embedded else self.pip]
- def get_paths(self) -> Dict[str, str]:
+ def get_paths(self) -> dict[str, str]:
# We can't use sysconfig.get_paths() because
# on some distributions it does not return the proper paths
# (those used by pip for instance). We go through distutils
@@ -1520,10 +1517,10 @@ def get_paths(self) -> Dict[str, str]:
return paths
- def get_supported_tags(self) -> List[Tag]:
+ def get_supported_tags(self) -> list[Tag]:
return list(sys_tags())
- def get_marker_env(self) -> Dict[str, Any]:
+ def get_marker_env(self) -> dict[str, Any]:
if hasattr(sys, "implementation"):
info = sys.implementation.version
iver = f"{info.major}.{info.minor}.{info.micro}"
@@ -1567,7 +1564,7 @@ class VirtualEnv(Env):
A virtual Python environment.
"""
- def __init__(self, path: Path, base: Optional[Path] = None) -> None:
+ def __init__(self, path: Path, base: Path | None = None) -> None:
super().__init__(path, base)
# If base is None, it probably means this is
@@ -1578,11 +1575,11 @@ def __init__(self, path: Path, base: Optional[Path] = None) -> None:
self._base = Path(self.run_python_script(GET_BASE_PREFIX).strip())
@property
- def sys_path(self) -> List[str]:
+ def sys_path(self) -> list[str]:
output = self.run_python_script(GET_SYS_PATH)
return json.loads(output)
- def get_version_info(self) -> Tuple[int]:
+ def get_version_info(self) -> tuple[int]:
output = self.run_python_script(GET_PYTHON_VERSION)
return tuple(int(s) for s in output.strip().split("."))
@@ -1590,7 +1587,7 @@ def get_version_info(self) -> Tuple[int]:
def get_python_implementation(self) -> str:
return self.marker_env["platform_python_implementation"]
- def get_pip_command(self, embedded: bool = False) -> List[str]:
+ def get_pip_command(self, embedded: bool = False) -> list[str]:
# We're in a virtualenv that is known to be sane,
# so assume that we have a functional pip
return [
@@ -1598,7 +1595,7 @@ def get_pip_command(self, embedded: bool = False) -> List[str]:
self.pip_embedded if embedded else self.pip,
]
- def get_supported_tags(self) -> List[Tag]:
+ def get_supported_tags(self) -> list[Tag]:
file_path = Path(packaging.tags.__file__)
if file_path.suffix == ".pyc":
# Python 2
@@ -1628,7 +1625,7 @@ def get_supported_tags(self) -> List[Tag]:
return [Tag(*t) for t in json.loads(output)]
- def get_marker_env(self) -> Dict[str, Any]:
+ def get_marker_env(self) -> dict[str, Any]:
output = self.run_python_script(GET_ENVIRONMENT_INFO)
return json.loads(output)
@@ -1641,7 +1638,7 @@ def get_pip_version(self) -> Version:
return Version.parse(m.group(1))
- def get_paths(self) -> Dict[str, str]:
+ def get_paths(self) -> dict[str, str]:
output = self.run_python_script(GET_PATHS)
return json.loads(output)
@@ -1652,16 +1649,16 @@ def is_sane(self) -> bool:
# A virtualenv is considered sane if "python" exists.
return os.path.exists(self.python)
- def _run(self, cmd: List[str], **kwargs: Any) -> Optional[int]:
+ def _run(self, cmd: list[str], **kwargs: Any) -> int | None:
kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env"))
return super()._run(cmd, **kwargs)
def get_temp_environ(
self,
- environ: Optional[Dict[str, str]] = None,
- exclude: Optional[List[str]] = None,
+ environ: dict[str, str] | None = None,
+ exclude: list[str] | None = None,
**kwargs: str,
- ) -> Dict[str, str]:
+ ) -> dict[str, str]:
exclude = exclude or []
exclude.extend(["PYTHONHOME", "__PYVENV_LAUNCHER__"])
@@ -1679,7 +1676,7 @@ def get_temp_environ(
return environ
- def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
+ def execute(self, bin: str, *args: str, **kwargs: Any) -> int | None:
kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env"))
return super().execute(bin, *args, **kwargs)
@@ -1698,7 +1695,7 @@ def _updated_path(self) -> str:
class GenericEnv(VirtualEnv):
def __init__(
- self, path: Path, base: Optional[Path] = None, child_env: Optional["Env"] = None
+ self, path: Path, base: Path | None = None, child_env: Env | None = None
) -> None:
self._child_env = child_env
@@ -1755,12 +1752,12 @@ def find_executables(self) -> None:
if pip_executable:
self._pip_executable = pip_executable
- def get_paths(self) -> Dict[str, str]:
+ def get_paths(self) -> dict[str, str]:
output = self.run_python_script(GET_PATHS_FOR_GENERIC_ENVS)
return json.loads(output)
- def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
+ def execute(self, bin: str, *args: str, **kwargs: Any) -> int | None:
command = self.get_command_from_bin(bin) + list(args)
env = kwargs.pop("env", dict(os.environ))
@@ -1772,7 +1769,7 @@ def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
return exe.returncode
- def _run(self, cmd: List[str], **kwargs: Any) -> Optional[int]:
+ def _run(self, cmd: list[str], **kwargs: Any) -> int | None:
return super(VirtualEnv, self)._run(cmd, **kwargs)
def is_venv(self) -> bool:
@@ -1781,7 +1778,7 @@ def is_venv(self) -> bool:
class NullEnv(SystemEnv):
def __init__(
- self, path: Path = None, base: Optional[Path] = None, execute: bool = False
+ self, path: Path = None, base: Path | None = None, execute: bool = False
) -> None:
if path is None:
path = Path(sys.prefix)
@@ -1791,20 +1788,20 @@ def __init__(
self._execute = execute
self.executed = []
- def get_pip_command(self, embedded: bool = False) -> List[str]:
+ def get_pip_command(self, embedded: bool = False) -> list[str]:
return [
self._bin(self._executable),
self.pip_embedded if embedded else self.pip,
]
- def _run(self, cmd: List[str], **kwargs: Any) -> Optional[int]:
+ def _run(self, cmd: list[str], **kwargs: Any) -> int | None:
self.executed.append(cmd)
if self._execute:
return super()._run(cmd, **kwargs)
return None
- def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
+ def execute(self, bin: str, *args: str, **kwargs: Any) -> int | None:
self.executed.append([bin] + list(args))
if self._execute:
@@ -1817,11 +1814,11 @@ def _bin(self, bin: str) -> str:
@contextmanager
def ephemeral_environment(
- executable: Optional[Union[str, Path]] = None,
- flags: Dict[str, bool] = None,
+ executable: str | Path | None = None,
+ flags: dict[str, bool] = None,
with_pip: bool = False,
- with_wheel: Optional[bool] = None,
- with_setuptools: Optional[bool] = None,
+ with_wheel: bool | None = None,
+ with_setuptools: bool | None = None,
) -> ContextManager[VirtualEnv]:
with temporary_directory() as tmp_dir:
# TODO: cache PEP 517 build environment corresponding to each project venv
@@ -1840,15 +1837,15 @@ def ephemeral_environment(
class MockEnv(NullEnv):
def __init__(
self,
- version_info: Tuple[int, int, int] = (3, 7, 0),
+ version_info: tuple[int, int, int] = (3, 7, 0),
python_implementation: str = "CPython",
platform: str = "darwin",
os_name: str = "posix",
is_venv: bool = False,
pip_version: str = "19.1",
- sys_path: Optional[List[str]] = None,
- marker_env: Dict[str, Any] = None,
- supported_tags: List[Tag] = None,
+ sys_path: list[str] | None = None,
+ marker_env: dict[str, Any] = None,
+ supported_tags: list[Tag] = None,
**kwargs: Any,
):
super().__init__(**kwargs)
@@ -1876,13 +1873,13 @@ def pip_version(self) -> Version:
return self._pip_version
@property
- def sys_path(self) -> List[str]:
+ def sys_path(self) -> list[str]:
if self._sys_path is None:
return super().sys_path
return self._sys_path
- def get_marker_env(self) -> Dict[str, Any]:
+ def get_marker_env(self) -> dict[str, Any]:
if self._mock_marker_env is not None:
return self._mock_marker_env
diff --git a/src/poetry/utils/exporter.py b/src/poetry/utils/exporter.py
index 98070d19b23..147b930fec2 100644
--- a/src/poetry/utils/exporter.py
+++ b/src/poetry/utils/exporter.py
@@ -1,10 +1,10 @@
+from __future__ import annotations
+
import itertools
import urllib.parse
from typing import TYPE_CHECKING
-from typing import Optional
from typing import Sequence
-from typing import Union
from poetry.core.packages.utils.utils import path_to_url
@@ -29,17 +29,17 @@ class Exporter:
ACCEPTED_FORMATS = (FORMAT_REQUIREMENTS_TXT,)
ALLOWED_HASH_ALGORITHMS = ("sha256", "sha384", "sha512")
- def __init__(self, poetry: "Poetry") -> None:
+ def __init__(self, poetry: Poetry) -> None:
self._poetry = poetry
def export(
self,
fmt: str,
- cwd: "Path",
- output: Union["IO", str],
+ cwd: Path,
+ output: IO | str,
with_hashes: bool = True,
dev: bool = False,
- extras: Optional[Union[bool, Sequence[str]]] = None,
+ extras: bool | Sequence[str] | None = None,
with_credentials: bool = False,
with_urls: bool = True,
) -> None:
@@ -58,11 +58,11 @@ def export(
def _export_requirements_txt(
self,
- cwd: "Path",
- output: Union["IO", str],
+ cwd: Path,
+ output: IO | str,
with_hashes: bool = True,
dev: bool = False,
- extras: Optional[Union[bool, Sequence[str]]] = None,
+ extras: bool | Sequence[str] | None = None,
with_credentials: bool = False,
with_urls: bool = True,
) -> None:
@@ -172,7 +172,7 @@ def _export_requirements_txt(
self._output(content, cwd, output)
- def _output(self, content: str, cwd: "Path", output: Union["IO", str]) -> None:
+ def _output(self, content: str, cwd: Path, output: IO | str) -> None:
decoded = decode(content)
try:
output.write(decoded)
diff --git a/src/poetry/utils/extras.py b/src/poetry/utils/extras.py
index 0b999fe5b1a..dc795225d15 100644
--- a/src/poetry/utils/extras.py
+++ b/src/poetry/utils/extras.py
@@ -1,7 +1,8 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from typing import Iterable
from typing import Iterator
-from typing import List
from typing import Mapping
from typing import Sequence
@@ -11,8 +12,8 @@
def get_extra_package_names(
- packages: Sequence["Package"],
- extras: Mapping[str, List[str]],
+ packages: Sequence[Package],
+ extras: Mapping[str, list[str]],
extra_names: Sequence[str],
) -> Iterable[str]:
"""
diff --git a/src/poetry/utils/helpers.py b/src/poetry/utils/helpers.py
index 4f7cf114e55..0a34cf6e6a6 100644
--- a/src/poetry/utils/helpers.py
+++ b/src/poetry/utils/helpers.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import re
import shutil
@@ -10,10 +12,7 @@
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
-from typing import Dict
from typing import Iterator
-from typing import List
-from typing import Optional
if TYPE_CHECKING:
@@ -48,7 +47,7 @@ def temporary_directory(*args: Any, **kwargs: Any) -> Iterator[str]:
shutil.rmtree(name, onerror=_del_ro)
-def get_cert(config: "Config", repository_name: str) -> Optional[Path]:
+def get_cert(config: Config, repository_name: str) -> Path | None:
cert = config.get(f"certificates.{repository_name}.cert")
if cert:
return Path(cert)
@@ -56,7 +55,7 @@ def get_cert(config: "Config", repository_name: str) -> Optional[Path]:
return None
-def get_client_cert(config: "Config", repository_name: str) -> Optional[Path]:
+def get_client_cert(config: Config, repository_name: str) -> Path | None:
client_cert = config.get(f"certificates.{repository_name}.client-cert")
if client_cert:
return Path(client_cert)
@@ -79,7 +78,7 @@ def safe_rmtree(path: str) -> None:
shutil.rmtree(path, onerror=_on_rm_error)
-def merge_dicts(d1: Dict, d2: Dict) -> None:
+def merge_dicts(d1: dict, d2: dict) -> None:
for k in d2.keys():
if k in d1 and isinstance(d1[k], dict) and isinstance(d2[k], Mapping):
merge_dicts(d1[k], d2[k])
@@ -90,7 +89,7 @@ def merge_dicts(d1: Dict, d2: Dict) -> None:
def download_file(
url: str,
dest: str,
- session: Optional["Session"] = None,
+ session: Session | None = None,
chunk_size: int = 1024,
) -> None:
import requests
@@ -107,7 +106,7 @@ def download_file(
def get_package_version_display_string(
- package: "Package", root: Optional[Path] = None
+ package: Package, root: Path | None = None
) -> str:
if package.source_type in ["file", "directory"] and root:
path = Path(os.path.relpath(package.source_url, root.as_posix())).as_posix()
@@ -116,7 +115,7 @@ def get_package_version_display_string(
return package.full_pretty_version
-def paths_csv(paths: List[Path]) -> str:
+def paths_csv(paths: list[Path]) -> str:
return ", ".join(f'"{c!s}"' for c in paths)
diff --git a/src/poetry/utils/password_manager.py b/src/poetry/utils/password_manager.py
index 17be50248ae..fcef51d157e 100644
--- a/src/poetry/utils/password_manager.py
+++ b/src/poetry/utils/password_manager.py
@@ -1,9 +1,9 @@
+from __future__ import annotations
+
import logging
from contextlib import suppress
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import Optional
if TYPE_CHECKING:
@@ -32,7 +32,7 @@ def __init__(self, namespace: str) -> None:
def is_available(self) -> bool:
return self._is_available
- def get_password(self, name: str, username: str) -> Optional[str]:
+ def get_password(self, name: str, username: str) -> str | None:
if not self.is_available():
return None
@@ -119,12 +119,12 @@ def _check(self) -> None:
class PasswordManager:
- def __init__(self, config: "Config") -> None:
+ def __init__(self, config: Config) -> None:
self._config = config
self._keyring = None
@property
- def keyring(self) -> Optional[KeyRing]:
+ def keyring(self) -> KeyRing | None:
if self._keyring is None:
self._keyring = KeyRing("poetry-repository")
if not self._keyring.is_available():
@@ -152,7 +152,7 @@ def delete_pypi_token(self, name: str) -> None:
self.keyring.delete_password(name, "__token__")
- def get_http_auth(self, name: str) -> Optional[Dict[str, str]]:
+ def get_http_auth(self, name: str) -> dict[str, str] | None:
auth = self._config.get(f"http-basic.{name}")
if not auth:
username = self._config.get(f"http-basic.{name}.username")
diff --git a/src/poetry/utils/patterns.py b/src/poetry/utils/patterns.py
index ec6c53d78d7..c0a196a15d3 100644
--- a/src/poetry/utils/patterns.py
+++ b/src/poetry/utils/patterns.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import re
diff --git a/src/poetry/utils/pip.py b/src/poetry/utils/pip.py
index e1d54d7e4a6..010e242d40d 100644
--- a/src/poetry/utils/pip.py
+++ b/src/poetry/utils/pip.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Union
from poetry.core.packages.utils.link import Link
from poetry.core.packages.utils.utils import url_to_path
@@ -15,12 +16,12 @@
def pip_install(
- path: Union["Path", Link],
- environment: "Env",
+ path: Path | Link,
+ environment: Env,
editable: bool = False,
deps: bool = False,
upgrade: bool = False,
-) -> Union[int, str]:
+) -> int | str:
path = url_to_path(path.url) if isinstance(path, Link) else path
is_wheel = path.suffix == ".whl"
@@ -54,9 +55,7 @@ def pip_install(
raise PoetryException(f"Failed to install {path.as_posix()}") from e
-def pip_editable_install(
- directory: Union["Path", Link], environment: "Env"
-) -> Union[int, str]:
+def pip_editable_install(directory: Path | Link, environment: Env) -> int | str:
return pip_install(
path=directory, environment=environment, editable=True, deps=False, upgrade=True
)
diff --git a/src/poetry/utils/setup_reader.py b/src/poetry/utils/setup_reader.py
index f8578658058..baac42c12ff 100644
--- a/src/poetry/utils/setup_reader.py
+++ b/src/poetry/utils/setup_reader.py
@@ -1,14 +1,11 @@
+from __future__ import annotations
+
import ast
from configparser import ConfigParser
from pathlib import Path
from typing import Any
-from typing import Dict
from typing import Iterable
-from typing import List
-from typing import Optional
-from typing import Tuple
-from typing import Union
from poetry.core.semver.version import Version
@@ -29,9 +26,7 @@ class SetupReader:
FILES = ["setup.py", "setup.cfg"]
@classmethod
- def read_from_directory(
- cls, directory: Union[str, Path]
- ) -> Dict[str, Union[List, Dict]]:
+ def read_from_directory(cls, directory: str | Path) -> dict[str, list | dict]:
if isinstance(directory, str):
directory = Path(directory)
@@ -50,7 +45,7 @@ def read_from_directory(
return result
- def read_setup_py(self, filepath: Union[str, Path]) -> Dict[str, Union[List, Dict]]:
+ def read_setup_py(self, filepath: str | Path) -> dict[str, list | dict]:
if isinstance(filepath, str):
filepath = Path(filepath)
@@ -76,9 +71,7 @@ def read_setup_py(self, filepath: Union[str, Path]) -> Dict[str, Union[List, Dic
return result
- def read_setup_cfg(
- self, filepath: Union[str, Path]
- ) -> Dict[str, Union[List, Dict]]:
+ def read_setup_cfg(self, filepath: str | Path) -> dict[str, list | dict]:
parser = ConfigParser()
parser.read(str(filepath))
@@ -126,8 +119,8 @@ def read_setup_cfg(
}
def _find_setup_call(
- self, elements: List[Any]
- ) -> Tuple[Optional[ast.Call], Optional[List[Any]]]:
+ self, elements: list[Any]
+ ) -> tuple[ast.Call | None, list[Any] | None]:
funcdefs = []
for i, element in enumerate(elements):
if isinstance(element, ast.If) and i == len(elements) - 1:
@@ -175,8 +168,8 @@ def _find_setup_call(
return self._find_sub_setup_call(funcdefs)
def _find_sub_setup_call(
- self, elements: List[Any]
- ) -> Tuple[Optional[ast.Call], Optional[List[Any]]]:
+ self, elements: list[Any]
+ ) -> tuple[ast.Call | None, list[Any] | None]:
for element in elements:
if not isinstance(element, (ast.FunctionDef, ast.If)):
continue
@@ -191,7 +184,7 @@ def _find_sub_setup_call(
return None, None
- def _find_install_requires(self, call: ast.Call, body: Iterable[Any]) -> List[str]:
+ def _find_install_requires(self, call: ast.Call, body: Iterable[Any]) -> list[str]:
install_requires = []
value = self._find_in_call(call, "install_requires")
if value is None:
@@ -233,7 +226,7 @@ def _find_install_requires(self, call: ast.Call, body: Iterable[Any]) -> List[st
def _find_extras_require(
self, call: ast.Call, body: Iterable[Any]
- ) -> Dict[str, List]:
+ ) -> dict[str, list]:
extras_require = {}
value = self._find_in_call(call, "extras_require")
if value is None:
@@ -284,8 +277,8 @@ def _find_extras_require(
return extras_require
def _find_single_string(
- self, call: ast.Call, body: List[Any], name: str
- ) -> Optional[str]:
+ self, call: ast.Call, body: list[Any], name: str
+ ) -> str | None:
value = self._find_in_call(call, name)
if value is None:
# Trying to find in kwargs
@@ -320,13 +313,13 @@ def _find_single_string(
if variable is not None and isinstance(variable, ast.Str):
return variable.s
- def _find_in_call(self, call: ast.Call, name: str) -> Optional[Any]:
+ def _find_in_call(self, call: ast.Call, name: str) -> Any | None:
for keyword in call.keywords:
if keyword.arg == name:
return keyword.value
return None
- def _find_call_kwargs(self, call: ast.Call) -> Optional[Any]:
+ def _find_call_kwargs(self, call: ast.Call) -> Any | None:
kwargs = None
for keyword in call.keywords:
if keyword.arg is None:
@@ -334,7 +327,7 @@ def _find_call_kwargs(self, call: ast.Call) -> Optional[Any]:
return kwargs
- def _find_variable_in_body(self, body: Iterable[Any], name: str) -> Optional[Any]:
+ def _find_variable_in_body(self, body: Iterable[Any], name: str) -> Any | None:
found = None
for elem in body:
if found:
@@ -350,9 +343,7 @@ def _find_variable_in_body(self, body: Iterable[Any], name: str) -> Optional[Any
if target.id == name:
return elem.value
- def _find_in_dict(
- self, dict_: Union[ast.Dict, ast.Call], name: str
- ) -> Optional[Any]:
+ def _find_in_dict(self, dict_: ast.Dict | ast.Call, name: str) -> Any | None:
for key, val in zip(dict_.keys, dict_.values):
if isinstance(key, ast.Str) and key.s == name:
return val
diff --git a/src/poetry/utils/shell.py b/src/poetry/utils/shell.py
index 01b6f638171..1a5de3c9cf5 100644
--- a/src/poetry/utils/shell.py
+++ b/src/poetry/utils/shell.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import signal
import subprocess
@@ -6,7 +8,6 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Optional
import pexpect
@@ -41,7 +42,7 @@ def path(self) -> str:
return self._path
@classmethod
- def get(cls) -> "Shell":
+ def get(cls) -> Shell:
"""
Retrieve the current shell.
"""
@@ -67,7 +68,7 @@ def get(cls) -> "Shell":
return cls._shell
- def activate(self, env: "VirtualEnv") -> Optional[int]:
+ def activate(self, env: VirtualEnv) -> int | None:
activate_script = self._get_activate_script()
bin_dir = "Scripts" if WINDOWS else "bin"
activate_path = env.path / bin_dir / activate_script
diff --git a/src/poetry/version/version_selector.py b/src/poetry/version/version_selector.py
index 68b3abdfd51..d40fcc7953a 100644
--- a/src/poetry/version/version_selector.py
+++ b/src/poetry/version/version_selector.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Optional
-from typing import Union
from poetry.core.semver.version import Version
@@ -12,16 +12,16 @@
class VersionSelector:
- def __init__(self, pool: "Pool") -> None:
+ def __init__(self, pool: Pool) -> None:
self._pool = pool
def find_best_candidate(
self,
package_name: str,
- target_package_version: Optional[str] = None,
+ target_package_version: str | None = None,
allow_prereleases: bool = False,
- source: Optional[str] = None,
- ) -> Union["Package", bool]:
+ source: str | None = None,
+ ) -> Package | bool:
"""
Given a package name and optional version,
returns the latest Package that matches
@@ -59,7 +59,7 @@ def find_best_candidate(
return False
return package
- def find_recommended_require_version(self, package: "Package") -> str:
+ def find_recommended_require_version(self, package: Package) -> str:
version = package.version
return self._transform_version(version.text, package.pretty_version)
diff --git a/tests/compat.py b/tests/compat.py
index 2181f8a9b97..aae06035ea7 100644
--- a/tests/compat.py
+++ b/tests/compat.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+
try:
import zipp
except ImportError:
diff --git a/tests/config/test_config.py b/tests/config/test_config.py
index 0f8c237c27d..985a7666ecb 100644
--- a/tests/config/test_config.py
+++ b/tests/config/test_config.py
@@ -1,10 +1,11 @@
+from __future__ import annotations
+
import os
import re
from typing import TYPE_CHECKING
from typing import Callable
from typing import Iterator
-from typing import Tuple
import pytest
@@ -35,12 +36,12 @@ def test_config_get_default_value(config: Config, name: str, value: bool):
def test_config_get_processes_depended_on_values(
- config: Config, config_cache_dir: "Path"
+ config: Config, config_cache_dir: Path
):
assert str(config_cache_dir / "virtualenvs") == config.get("virtualenvs.path")
-def generate_environment_variable_tests() -> Iterator[Tuple[str, str, str, bool]]:
+def generate_environment_variable_tests() -> Iterator[tuple[str, str, str, bool]]:
for normalizer, values in [
(boolean_normalizer, [("true", True), ("false", False)]),
(int_normalizer, [("4", 4), ("2", 2)]),
diff --git a/tests/conftest.py b/tests/conftest.py
index a1b4d486e57..f35ca1bfdc9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import re
import shutil
@@ -8,13 +10,8 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
from typing import Iterator
-from typing import List
-from typing import Optional
from typing import TextIO
-from typing import Tuple
-from typing import Type
import httpretty
import pytest
@@ -62,13 +59,13 @@ def get(self, setting_name: str, default: Any = None) -> Any:
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._auth_config_source.config)
return super().raw()
- def all(self) -> Dict[str, Any]:
+ def all(self) -> dict[str, Any]:
self.merge(self._config_source.config)
self.merge(self._auth_config_source.config)
@@ -83,18 +80,16 @@ def __init__(self) -> None:
def priority(cls) -> int:
return 42
- def set_password(
- self, service: str, username: Optional[str], password: Any
- ) -> None:
+ def set_password(self, service: str, username: str | None, password: Any) -> None:
self._passwords[service] = {username: password}
- def get_password(self, service: str, username: Optional[str]) -> Any:
+ def get_password(self, service: str, username: str | None) -> Any:
return self._passwords.get(service, {}).get(username)
- def get_credential(self, service: str, username: Optional[str]) -> Any:
+ def get_credential(self, service: str, username: str | None) -> Any:
return self._passwords.get(service, {}).get(username)
- def delete_password(self, service: str, username: Optional[str]) -> None:
+ def delete_password(self, service: str, username: str | None) -> None:
if service in self._passwords and username in self._passwords[service]:
del self._passwords[service][username]
@@ -121,7 +116,7 @@ def with_fail_keyring() -> None:
@pytest.fixture()
-def with_chained_keyring(mocker: "MockerFixture") -> None:
+def with_chained_keyring(mocker: MockerFixture) -> None:
from keyring.backends.fail import Keyring
mocker.patch("keyring.backend.get_all_keyring", [Keyring()])
@@ -163,7 +158,7 @@ def auth_config_source() -> DictConfigSource:
def config(
config_source: DictConfigSource,
auth_config_source: DictConfigSource,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
) -> Config:
import keyring
@@ -183,7 +178,7 @@ def config(
@pytest.fixture(autouse=True)
-def mock_user_config_dir(mocker: "MockerFixture") -> Iterator[None]:
+def mock_user_config_dir(mocker: MockerFixture) -> Iterator[None]:
config_dir = tempfile.mkdtemp(prefix="poetry_config_")
mocker.patch("poetry.locations.CONFIG_DIR", new=config_dir)
mocker.patch("poetry.factory.CONFIG_DIR", new=config_dir)
@@ -192,7 +187,7 @@ def mock_user_config_dir(mocker: "MockerFixture") -> Iterator[None]:
@pytest.fixture(autouse=True)
-def download_mock(mocker: "MockerFixture") -> None:
+def download_mock(mocker: MockerFixture) -> None:
# Patch download to not download anything but to just copy from fixtures
mocker.patch("poetry.utils.helpers.download_file", new=mock_download)
mocker.patch("poetry.puzzle.provider.download_file", new=mock_download)
@@ -200,7 +195,7 @@ def download_mock(mocker: "MockerFixture") -> None:
@pytest.fixture(autouse=True)
-def pep517_metadata_mock(mocker: "MockerFixture") -> None:
+def pep517_metadata_mock(mocker: MockerFixture) -> None:
@classmethod
def _pep517_metadata(cls: PackageInfo, path: Path) -> PackageInfo:
with suppress(PackageInfoError):
@@ -224,7 +219,7 @@ def environ() -> Iterator[None]:
@pytest.fixture(autouse=True)
-def git_mock(mocker: "MockerFixture") -> None:
+def git_mock(mocker: MockerFixture) -> None:
# Patch git module to not actually clone projects
mocker.patch("poetry.core.vcs.git.Git.clone", new=mock_clone)
mocker.patch("poetry.core.vcs.git.Git.checkout", new=lambda *_: None)
@@ -233,7 +228,7 @@ def git_mock(mocker: "MockerFixture") -> None:
@pytest.fixture
-def http() -> Iterator[Type[httpretty.httpretty]]:
+def http() -> Iterator[type[httpretty.httpretty]]:
httpretty.reset()
httpretty.enable(allow_net_connect=False)
@@ -249,7 +244,7 @@ def fixture_base() -> Path:
@pytest.fixture
-def fixture_dir(fixture_base: Path) -> "FixtureDirGetter":
+def fixture_dir(fixture_base: Path) -> FixtureDirGetter:
def _fixture_dir(name: str) -> Path:
return fixture_base / name
@@ -266,7 +261,7 @@ def tmp_dir() -> Iterator[str]:
@pytest.fixture
-def mocked_open_files(mocker: "MockerFixture") -> List:
+def mocked_open_files(mocker: MockerFixture) -> list:
files = []
original = Path.open
@@ -303,17 +298,17 @@ def current_env() -> SystemEnv:
@pytest.fixture(scope="session")
-def current_python(current_env: SystemEnv) -> Tuple[int, int, int]:
+def current_python(current_env: SystemEnv) -> tuple[int, int, int]:
return current_env.version_info[:3]
@pytest.fixture(scope="session")
-def default_python(current_python: Tuple[int, int, int]) -> str:
+def default_python(current_python: tuple[int, int, int]) -> str:
return "^" + ".".join(str(v) for v in current_python[:2])
@pytest.fixture
-def repo(http: Type[httpretty.httpretty]) -> TestRepository:
+def repo(http: type[httpretty.httpretty]) -> TestRepository:
http.register_uri(
http.GET,
re.compile("^https?://foo.bar/(.+?)$"),
@@ -328,17 +323,17 @@ def project_factory(
repo: TestRepository,
installed: Repository,
default_python: str,
-) -> "ProjectFactory":
+) -> ProjectFactory:
workspace = Path(tmp_dir)
def _factory(
- name: Optional[str] = None,
- dependencies: Optional[Dict[str, str]] = None,
- dev_dependencies: Optional[Dict[str, str]] = None,
- pyproject_content: Optional[str] = None,
- poetry_lock_content: Optional[str] = None,
+ name: str | None = None,
+ dependencies: dict[str, str] | None = None,
+ dev_dependencies: dict[str, str] | None = None,
+ pyproject_content: str | None = None,
+ poetry_lock_content: str | None = None,
install_deps: bool = True,
- ) -> "Poetry":
+ ) -> Poetry:
project_dir = workspace / f"poetry-fixture-{name}"
dependencies = dependencies or {}
dev_dependencies = dev_dependencies or {}
@@ -391,14 +386,14 @@ def _factory(
@pytest.fixture
def command_tester_factory(
- app: "PoetryTestApplication", env: "MockEnv"
-) -> "CommandTesterFactory":
+ app: PoetryTestApplication, env: MockEnv
+) -> CommandTesterFactory:
def _tester(
command: str,
- poetry: Optional["Poetry"] = None,
- installer: Optional[Installer] = None,
- executor: Optional["Executor"] = None,
- environment: Optional["Env"] = None,
+ poetry: Poetry | None = None,
+ installer: Installer | None = None,
+ executor: Executor | None = None,
+ environment: Env | None = None,
) -> CommandTester:
command = app.find(command)
tester = CommandTester(command)
@@ -439,7 +434,7 @@ def _tester(
@pytest.fixture
-def do_lock(command_tester_factory: "CommandTesterFactory", poetry: "Poetry") -> None:
+def do_lock(command_tester_factory: CommandTesterFactory, poetry: Poetry) -> None:
command_tester_factory("lock").execute()
assert poetry.locker.lock.exists()
diff --git a/tests/console/commands/debug/test_resolve.py b/tests/console/commands/debug/test_resolve.py
index d768b8d7756..ddb45d4d1c8 100644
--- a/tests/console/commands/debug/test_resolve.py
+++ b/tests/console/commands/debug/test_resolve.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -14,12 +16,12 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("debug resolve")
@pytest.fixture(autouse=True)
-def __add_packages(repo: "TestRepository") -> None:
+def __add_packages(repo: TestRepository) -> None:
cachy020 = get_package("cachy", "0.2.0")
cachy020.add_dependency(Factory.create_dependency("msgpack-python", ">=0.5 <0.6"))
@@ -31,7 +33,7 @@ def __add_packages(repo: "TestRepository") -> None:
repo.add_package(get_package("cleo", "0.6.5"))
-def test_debug_resolve_gives_resolution_results(tester: "CommandTester"):
+def test_debug_resolve_gives_resolution_results(tester: CommandTester):
tester.execute("cachy")
expected = """\
@@ -46,7 +48,7 @@ def test_debug_resolve_gives_resolution_results(tester: "CommandTester"):
assert tester.io.fetch_output() == expected
-def test_debug_resolve_tree_option_gives_the_dependency_tree(tester: "CommandTester"):
+def test_debug_resolve_tree_option_gives_the_dependency_tree(tester: CommandTester):
tester.execute("cachy --tree")
expected = """\
@@ -61,7 +63,7 @@ def test_debug_resolve_tree_option_gives_the_dependency_tree(tester: "CommandTes
assert tester.io.fetch_output() == expected
-def test_debug_resolve_git_dependency(tester: "CommandTester"):
+def test_debug_resolve_git_dependency(tester: CommandTester):
tester.execute("git+https://github.com/demo/demo.git")
expected = """\
diff --git a/tests/console/commands/env/conftest.py b/tests/console/commands/env/conftest.py
index d4137bca387..408f4319aa4 100644
--- a/tests/console/commands/env/conftest.py
+++ b/tests/console/commands/env/conftest.py
@@ -1,9 +1,10 @@
+from __future__ import annotations
+
import os
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Iterator
-from typing import List
import pytest
@@ -15,7 +16,7 @@
@pytest.fixture
-def venv_name(app: "PoetryTestApplication") -> str:
+def venv_name(app: PoetryTestApplication) -> str:
return EnvManager.generate_env_name("simple-project", str(app.poetry.file.parent))
@@ -25,23 +26,23 @@ def venv_cache(tmp_dir: str) -> Path:
@pytest.fixture(scope="module")
-def python_versions() -> List[str]:
+def python_versions() -> list[str]:
return ["3.6", "3.7"]
@pytest.fixture
-def venvs_in_cache_config(app: "PoetryTestApplication", venv_cache: Path) -> None:
+def venvs_in_cache_config(app: PoetryTestApplication, venv_cache: Path) -> None:
app.poetry.config.merge({"virtualenvs": {"path": str(venv_cache)}})
@pytest.fixture
def venvs_in_cache_dirs(
- app: "PoetryTestApplication",
+ app: PoetryTestApplication,
venvs_in_cache_config: None,
venv_name: str,
venv_cache: Path,
- python_versions: List[str],
-) -> List[str]:
+ python_versions: list[str],
+) -> list[str]:
directories = []
for version in python_versions:
directory = venv_cache.joinpath(f"{venv_name}-py{version}")
@@ -51,7 +52,7 @@ def venvs_in_cache_dirs(
@pytest.fixture
-def venvs_in_project_dir(app: "PoetryTestApplication") -> Iterator[Path]:
+def venvs_in_project_dir(app: PoetryTestApplication) -> Iterator[Path]:
os.environ.pop("VIRTUAL_ENV", None)
venv_dir = app.poetry.file.parent.joinpath(".venv")
venv_dir.mkdir(exist_ok=True)
diff --git a/tests/console/commands/env/helpers.py b/tests/console/commands/env/helpers.py
index 23d1e1e8d1c..97058c796cb 100644
--- a/tests/console/commands/env/helpers.py
+++ b/tests/console/commands/env/helpers.py
@@ -1,8 +1,9 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
-from typing import Union
from poetry.core.semver.version import Version
@@ -13,12 +14,12 @@
VERSION_3_7_1 = Version.parse("3.7.1")
-def build_venv(path: Union[Path, str], **_: Any) -> None:
+def build_venv(path: Path | str, **_: Any) -> None:
Path(path).mkdir(parents=True, exist_ok=True)
def check_output_wrapper(
- version: "PEP440Version" = VERSION_3_7_1,
+ version: PEP440Version = VERSION_3_7_1,
) -> Callable[[str, Any, Any], str]:
def check_output(cmd: str, *_: Any, **__: Any) -> str:
if "sys.version_info[:3]" in cmd:
diff --git a/tests/console/commands/env/test_info.py b/tests/console/commands/env/test_info.py
index 73bbf2a1b41..e4f5826e49c 100644
--- a/tests/console/commands/env/test_info.py
+++ b/tests/console/commands/env/test_info.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import sys
from pathlib import Path
@@ -16,7 +18,7 @@
@pytest.fixture(autouse=True)
-def setup(mocker: "MockerFixture") -> None:
+def setup(mocker: MockerFixture) -> None:
mocker.patch(
"poetry.utils.env.EnvManager.get",
return_value=MockEnv(
@@ -26,11 +28,11 @@ def setup(mocker: "MockerFixture") -> None:
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("env info")
-def test_env_info_displays_complete_info(tester: "CommandTester"):
+def test_env_info_displays_complete_info(tester: CommandTester):
tester.execute()
expected = f"""
@@ -52,7 +54,7 @@ def test_env_info_displays_complete_info(tester: "CommandTester"):
assert tester.io.fetch_output() == expected
-def test_env_info_displays_path_only(tester: "CommandTester"):
+def test_env_info_displays_path_only(tester: CommandTester):
tester.execute("--path")
expected = str(Path("/prefix")) + "\n"
assert tester.io.fetch_output() == expected
diff --git a/tests/console/commands/env/test_list.py b/tests/console/commands/env/test_list.py
index 13f6b5f46de..2f284470bbd 100644
--- a/tests/console/commands/env/test_list.py
+++ b/tests/console/commands/env/test_list.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
import pytest
import tomlkit
@@ -18,7 +19,7 @@
@pytest.fixture
-def venv_activate_37(venv_cache: "Path", venv_name: str) -> None:
+def venv_activate_37(venv_cache: Path, venv_name: str) -> None:
envs_file = TOMLFile(venv_cache / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
@@ -26,15 +27,15 @@ def venv_activate_37(venv_cache: "Path", venv_name: str) -> None:
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("env list")
def test_none_activated(
- tester: "CommandTester",
- venvs_in_cache_dirs: List[str],
- mocker: "MockerFixture",
- env: "MockEnv",
+ tester: CommandTester,
+ venvs_in_cache_dirs: list[str],
+ mocker: MockerFixture,
+ env: MockEnv,
):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=env)
tester.execute()
@@ -43,9 +44,9 @@ def test_none_activated(
def test_activated(
- tester: "CommandTester",
- venvs_in_cache_dirs: List[str],
- venv_cache: "Path",
+ tester: CommandTester,
+ venvs_in_cache_dirs: list[str],
+ venv_cache: Path,
venv_activate_37: None,
):
tester.execute()
@@ -55,7 +56,7 @@ def test_activated(
assert tester.io.fetch_output().strip() == expected
-def test_in_project_venv(tester: "CommandTester", venvs_in_project_dir: List[str]):
+def test_in_project_venv(tester: CommandTester, venvs_in_project_dir: list[str]):
tester.execute()
expected = ".venv (Activated)\n"
assert tester.io.fetch_output() == expected
diff --git a/tests/console/commands/env/test_remove.py b/tests/console/commands/env/test_remove.py
index e0724f8f65b..0511e4ec25b 100644
--- a/tests/console/commands/env/test_remove.py
+++ b/tests/console/commands/env/test_remove.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import List
import pytest
@@ -18,16 +19,16 @@
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("env remove")
def test_remove_by_python_version(
- mocker: "MockerFixture",
- tester: "CommandTester",
- venvs_in_cache_dirs: List[str],
+ mocker: MockerFixture,
+ tester: CommandTester,
+ venvs_in_cache_dirs: list[str],
venv_name: str,
- venv_cache: "Path",
+ venv_cache: Path,
):
check_output = mocker.patch(
"subprocess.check_output",
@@ -44,10 +45,10 @@ def test_remove_by_python_version(
def test_remove_by_name(
- tester: "CommandTester",
- venvs_in_cache_dirs: List[str],
+ tester: CommandTester,
+ venvs_in_cache_dirs: list[str],
venv_name: str,
- venv_cache: "Path",
+ venv_cache: Path,
):
expected = ""
@@ -62,10 +63,10 @@ def test_remove_by_name(
def test_remove_all(
- tester: "CommandTester",
- venvs_in_cache_dirs: List[str],
+ tester: CommandTester,
+ venvs_in_cache_dirs: list[str],
venv_name: str,
- venv_cache: "Path",
+ venv_cache: Path,
):
expected = {""}
tester.execute("--all")
@@ -76,10 +77,10 @@ def test_remove_all(
def test_remove_all_and_version(
- tester: "CommandTester",
- venvs_in_cache_dirs: List[str],
+ tester: CommandTester,
+ venvs_in_cache_dirs: list[str],
venv_name: str,
- venv_cache: "Path",
+ venv_cache: Path,
):
expected = {""}
tester.execute(f"--all {venvs_in_cache_dirs[0]}")
@@ -90,10 +91,10 @@ def test_remove_all_and_version(
def test_remove_multiple(
- tester: "CommandTester",
- venvs_in_cache_dirs: List[str],
+ tester: CommandTester,
+ venvs_in_cache_dirs: list[str],
venv_name: str,
- venv_cache: "Path",
+ venv_cache: Path,
):
expected = {""}
removed_envs = venvs_in_cache_dirs[0:2]
diff --git a/tests/console/commands/env/test_use.py b/tests/console/commands/env/test_use.py
index 95d365ec882..34bbf9ad0da 100644
--- a/tests/console/commands/env/test_use.py
+++ b/tests/console/commands/env/test_use.py
@@ -1,8 +1,9 @@
+from __future__ import annotations
+
import os
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Tuple
import pytest
import tomlkit
@@ -23,7 +24,7 @@
@pytest.fixture(autouse=True)
-def setup(mocker: "MockerFixture") -> None:
+def setup(mocker: MockerFixture) -> None:
mocker.stopall()
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -31,7 +32,7 @@ def setup(mocker: "MockerFixture") -> None:
@pytest.fixture(autouse=True)
def mock_subprocess_calls(
- setup: None, current_python: Tuple[int, int, int], mocker: "MockerFixture"
+ setup: None, current_python: tuple[int, int, int], mocker: MockerFixture
) -> None:
mocker.patch(
"subprocess.check_output",
@@ -44,13 +45,13 @@ def mock_subprocess_calls(
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("env use")
def test_activate_activates_non_existing_virtualenv_no_envs_file(
- mocker: "MockerFixture",
- tester: "CommandTester",
+ mocker: MockerFixture,
+ tester: CommandTester,
venv_cache: Path,
venv_name: str,
venvs_in_cache_config: None,
@@ -91,8 +92,8 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file(
def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
- tester: "CommandTester",
- current_python: Tuple[int, int, int],
+ tester: CommandTester,
+ current_python: tuple[int, int, int],
venv_cache: Path,
venv_name: str,
venvs_in_cache_config: None,
@@ -119,9 +120,9 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
def test_get_prefers_explicitly_activated_non_existing_virtualenvs_over_env_var(
- mocker: "MockerFixture",
- tester: "CommandTester",
- current_python: Tuple[int, int, int],
+ mocker: MockerFixture,
+ tester: CommandTester,
+ current_python: tuple[int, int, int],
venv_cache: Path,
venv_name: str,
venvs_in_cache_config: None,
diff --git a/tests/console/commands/plugin/conftest.py b/tests/console/commands/plugin/conftest.py
index c73f1db2ef7..2c7f19f264c 100644
--- a/tests/console/commands/plugin/conftest.py
+++ b/tests/console/commands/plugin/conftest.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -33,9 +35,9 @@ def installed() -> InstalledRepository:
return repository
-def configure_sources_factory(repo: "TestRepository") -> "SourcesFactory":
+def configure_sources_factory(repo: TestRepository) -> SourcesFactory:
def _configure_sources(
- poetry: "Poetry", sources: "Source", config: "Config", io: "IO"
+ poetry: Poetry, sources: Source, config: Config, io: IO
) -> None:
pool = Pool()
pool.add_repository(repo)
@@ -46,10 +48,10 @@ def _configure_sources(
@pytest.fixture(autouse=True)
def setup_mocks(
- mocker: "MockerFixture",
- env: "MockEnv",
- repo: "TestRepository",
- installed: "Repository",
+ mocker: MockerFixture,
+ env: MockEnv,
+ repo: TestRepository,
+ installed: Repository,
) -> None:
mocker.patch.object(EnvManager, "get_system_env", return_value=env)
mocker.patch.object(InstalledRepository, "load", return_value=installed)
diff --git a/tests/console/commands/plugin/test_add.py b/tests/console/commands/plugin/test_add.py
index c26ccde4da8..2eef6384972 100644
--- a/tests/console/commands/plugin/test_add.py
+++ b/tests/console/commands/plugin/test_add.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import Union
import pytest
@@ -22,20 +22,20 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("plugin add")
def assert_plugin_add_result(
- tester: "CommandTester",
- app: "PoetryTestApplication",
- env: "MockEnv",
+ tester: CommandTester,
+ app: PoetryTestApplication,
+ env: MockEnv,
expected: str,
- constraint: Union[str, Dict[str, str]],
+ constraint: str | dict[str, str],
) -> None:
assert tester.io.fetch_output() == expected
- update_command: "UpdateCommand" = app.find("update")
+ update_command: UpdateCommand = app.find("update")
assert update_command.poetry.file.parent == env.path
assert update_command.poetry.locker.lock.parent == env.path
assert update_command.poetry.locker.lock.exists()
@@ -46,11 +46,11 @@ def assert_plugin_add_result(
def test_add_no_constraint(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
- installed: "Repository",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
+ installed: Repository,
):
repo.add_package(Package("poetry-plugin", "0.1.0"))
@@ -71,11 +71,11 @@ def test_add_no_constraint(
def test_add_with_constraint(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
- installed: "Repository",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
+ installed: Repository,
):
repo.add_package(Package("poetry-plugin", "0.1.0"))
repo.add_package(Package("poetry-plugin", "0.2.0"))
@@ -97,11 +97,11 @@ def test_add_with_constraint(
def test_add_with_git_constraint(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
- installed: "Repository",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
+ installed: Repository,
):
repo.add_package(Package("pendulum", "2.0.5"))
@@ -125,11 +125,11 @@ def test_add_with_git_constraint(
def test_add_with_git_constraint_with_extras(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
- installed: "Repository",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
+ installed: Repository,
):
repo.add_package(Package("pendulum", "2.0.5"))
repo.add_package(Package("tomlkit", "0.7.0"))
@@ -162,11 +162,11 @@ def test_add_with_git_constraint_with_extras(
def test_add_existing_plugin_warns_about_no_operation(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
- installed: "Repository",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
+ installed: Repository,
):
env.path.joinpath("pyproject.toml").write_text(
"""\
@@ -206,18 +206,18 @@ def test_add_existing_plugin_warns_about_no_operation(
assert tester.io.fetch_output() == expected
- update_command: "UpdateCommand" = app.find("update")
+ update_command: UpdateCommand = app.find("update")
# The update command should not have been called
assert update_command.poetry.file.parent != env.path
def test_add_existing_plugin_updates_if_requested(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
- installed: "Repository",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
+ installed: Repository,
+ mocker: MockerFixture,
):
env.path.joinpath("pyproject.toml").write_text(
"""\
@@ -259,11 +259,11 @@ def test_add_existing_plugin_updates_if_requested(
def test_adding_a_plugin_can_update_poetry_dependencies_if_needed(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
- installed: "Repository",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
+ installed: Repository,
):
poetry_package = Package("poetry", "1.2.0")
poetry_package.add_dependency(Factory.create_dependency("tomlkit", "^0.7.0"))
diff --git a/tests/console/commands/plugin/test_remove.py b/tests/console/commands/plugin/test_remove.py
index 7a4a0970fc6..01cdc9017f6 100644
--- a/tests/console/commands/plugin/test_remove.py
+++ b/tests/console/commands/plugin/test_remove.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -20,12 +22,12 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("plugin remove")
@pytest.fixture()
-def pyproject(env: "MockEnv") -> None:
+def pyproject(env: MockEnv) -> None:
pyproject = tomlkit.loads(POETRY_DEFAULT)
content = pyproject["tool"]["poetry"]
@@ -43,7 +45,7 @@ def pyproject(env: "MockEnv") -> None:
@pytest.fixture(autouse=True)
-def install_plugin(env: "MockEnv", installed: "Repository", pyproject: None) -> None:
+def install_plugin(env: MockEnv, installed: Repository, pyproject: None) -> None:
lock_content = {
"package": [
{
@@ -84,7 +86,7 @@ def install_plugin(env: "MockEnv", installed: "Repository", pyproject: None) ->
def test_remove_installed_package(
- app: "PoetryTestApplication", tester: "CommandTester", env: "MockEnv"
+ app: PoetryTestApplication, tester: CommandTester, env: MockEnv
):
tester.execute("poetry-plugin")
@@ -101,7 +103,7 @@ def test_remove_installed_package(
assert tester.io.fetch_output() == expected
- remove_command: "RemoveCommand" = app.find("remove")
+ remove_command: RemoveCommand = app.find("remove")
assert remove_command.poetry.file.parent == env.path
assert remove_command.poetry.locker.lock.parent == env.path
assert remove_command.poetry.locker.lock.exists()
@@ -112,7 +114,7 @@ def test_remove_installed_package(
def test_remove_installed_package_dry_run(
- app: "PoetryTestApplication", tester: "CommandTester", env: "MockEnv"
+ app: PoetryTestApplication, tester: CommandTester, env: MockEnv
):
tester.execute("poetry-plugin --dry-run")
@@ -130,7 +132,7 @@ def test_remove_installed_package_dry_run(
assert tester.io.fetch_output() == expected
- remove_command: "RemoveCommand" = app.find("remove")
+ remove_command: RemoveCommand = app.find("remove")
assert remove_command.poetry.file.parent == env.path
assert remove_command.poetry.locker.lock.parent == env.path
assert remove_command.poetry.locker.lock.exists()
diff --git a/tests/console/commands/plugin/test_show.py b/tests/console/commands/plugin/test_show.py
index 9d0dca4abd0..4257d3ea695 100644
--- a/tests/console/commands/plugin/test_show.py
+++ b/tests/console/commands/plugin/test_show.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Type
import pytest
@@ -22,7 +23,7 @@
class EntryPoint(_EntryPoint):
- def load(self) -> Type["BasePlugin"]:
+ def load(self) -> type[BasePlugin]:
if "ApplicationPlugin" in self.object_name:
return ApplicationPlugin
@@ -30,15 +31,15 @@ def load(self) -> Type["BasePlugin"]:
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("plugin show")
def test_show_displays_installed_plugins(
- app: "PoetryTestApplication",
- tester: "CommandTester",
- installed: "Repository",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ tester: CommandTester,
+ installed: Repository,
+ mocker: MockerFixture,
):
mocker.patch(
"entrypoints.get_group_all",
@@ -73,10 +74,10 @@ def test_show_displays_installed_plugins(
def test_show_displays_installed_plugins_with_multiple_plugins(
- app: "PoetryTestApplication",
- tester: "CommandTester",
- installed: "Repository",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ tester: CommandTester,
+ installed: Repository,
+ mocker: MockerFixture,
):
mocker.patch(
"entrypoints.get_group_all",
@@ -121,10 +122,10 @@ def test_show_displays_installed_plugins_with_multiple_plugins(
def test_show_displays_installed_plugins_with_dependencies(
- app: "PoetryTestApplication",
- tester: "CommandTester",
- installed: "Repository",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ tester: CommandTester,
+ installed: Repository,
+ mocker: MockerFixture,
):
mocker.patch(
"entrypoints.get_group_all",
diff --git a/tests/console/commands/self/test_update.py b/tests/console/commands/self/test_update.py
index 33c60dbf39c..076683eb90d 100644
--- a/tests/console/commands/self/test_update.py
+++ b/tests/console/commands/self/test_update.py
@@ -1,6 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Type
import pytest
@@ -29,16 +30,16 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("self update")
def test_self_update_can_update_from_recommended_installation(
- tester: "CommandTester",
- http: Type["httpretty.httpretty"],
- mocker: "MockerFixture",
+ tester: CommandTester,
+ http: type[httpretty.httpretty],
+ mocker: MockerFixture,
environ: None,
- tmp_venv: "VirtualEnv",
+ tmp_venv: VirtualEnv,
):
mocker.patch.object(EnvManager, "get_system_env", return_value=tmp_venv)
@@ -90,11 +91,11 @@ def test_self_update_can_update_from_recommended_installation(
def test_self_update_does_not_update_non_recommended_installation(
- tester: "CommandTester",
- http: Type["httpretty.httpretty"],
- mocker: "MockerFixture",
+ tester: CommandTester,
+ http: type[httpretty.httpretty],
+ mocker: MockerFixture,
environ: None,
- tmp_venv: "VirtualEnv",
+ tmp_venv: VirtualEnv,
):
mocker.patch.object(EnvManager, "get_system_env", return_value=tmp_venv)
diff --git a/tests/console/commands/source/conftest.py b/tests/console/commands/source/conftest.py
index 2630501b66c..254b3454297 100644
--- a/tests/console/commands/source/conftest.py
+++ b/tests/console/commands/source/conftest.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -58,14 +60,14 @@ def source_existing() -> Source:
@pytest.fixture
-def poetry_with_source(project_factory: "ProjectFactory") -> "Poetry":
+def poetry_with_source(project_factory: ProjectFactory) -> Poetry:
return project_factory(pyproject_content=PYPROJECT_WITH_SOURCES)
@pytest.fixture
def add_multiple_sources(
- command_tester_factory: "CommandTesterFactory",
- poetry_with_source: "Poetry",
+ command_tester_factory: CommandTesterFactory,
+ poetry_with_source: Poetry,
source_one: Source,
source_two: Source,
) -> None:
diff --git a/tests/console/commands/source/test_add.py b/tests/console/commands/source/test_add.py
index 7afbc15e36d..7e43b9e2014 100644
--- a/tests/console/commands/source/test_add.py
+++ b/tests/console/commands/source/test_add.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import dataclasses
from typing import TYPE_CHECKING
@@ -15,16 +17,16 @@
@pytest.fixture
def tester(
- command_tester_factory: "CommandTesterFactory", poetry_with_source: "Poetry"
-) -> "CommandTester":
+ command_tester_factory: CommandTesterFactory, poetry_with_source: Poetry
+) -> CommandTester:
return command_tester_factory("source add", poetry=poetry_with_source)
def assert_source_added(
- tester: "CommandTester",
- poetry: "Poetry",
- source_existing: "Source",
- source_added: "Source",
+ tester: CommandTester,
+ poetry: Poetry,
+ source_existing: Source,
+ source_added: Source,
) -> None:
assert (
tester.io.fetch_output().strip()
@@ -37,36 +39,36 @@ def assert_source_added(
def test_source_add_simple(
- tester: "CommandTester",
- source_existing: "Source",
- source_one: "Source",
- poetry_with_source: "Poetry",
+ tester: CommandTester,
+ source_existing: Source,
+ source_one: Source,
+ poetry_with_source: Poetry,
):
tester.execute(f"{source_one.name} {source_one.url}")
assert_source_added(tester, poetry_with_source, source_existing, source_one)
def test_source_add_default(
- tester: "CommandTester",
- source_existing: "Source",
- source_default: "Source",
- poetry_with_source: "Poetry",
+ tester: CommandTester,
+ source_existing: Source,
+ source_default: Source,
+ poetry_with_source: Poetry,
):
tester.execute(f"--default {source_default.name} {source_default.url}")
assert_source_added(tester, poetry_with_source, source_existing, source_default)
def test_source_add_secondary(
- tester: "CommandTester",
- source_existing: "Source",
- source_secondary: "Source",
- poetry_with_source: "Poetry",
+ tester: CommandTester,
+ source_existing: Source,
+ source_secondary: Source,
+ poetry_with_source: Poetry,
):
tester.execute(f"--secondary {source_secondary.name} {source_secondary.url}")
assert_source_added(tester, poetry_with_source, source_existing, source_secondary)
-def test_source_add_error_default_and_secondary(tester: "CommandTester"):
+def test_source_add_error_default_and_secondary(tester: CommandTester):
tester.execute("--default --secondary error https://error.com")
assert (
tester.io.fetch_error().strip()
@@ -75,7 +77,7 @@ def test_source_add_error_default_and_secondary(tester: "CommandTester"):
assert tester.status_code == 1
-def test_source_add_error_pypi(tester: "CommandTester"):
+def test_source_add_error_pypi(tester: CommandTester):
tester.execute("pypi https://test.pypi.org/simple/")
assert (
tester.io.fetch_error().strip()
@@ -86,7 +88,7 @@ def test_source_add_error_pypi(tester: "CommandTester"):
def test_source_add_existing(
- tester: "CommandTester", source_existing: "Source", poetry_with_source: "Poetry"
+ tester: CommandTester, source_existing: Source, poetry_with_source: Poetry
):
tester.execute(f"--default {source_existing.name} {source_existing.url}")
assert (
diff --git a/tests/console/commands/source/test_remove.py b/tests/console/commands/source/test_remove.py
index 02dd735ef47..914eb3e03b3 100644
--- a/tests/console/commands/source/test_remove.py
+++ b/tests/console/commands/source/test_remove.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -13,19 +15,19 @@
@pytest.fixture
def tester(
- command_tester_factory: "CommandTesterFactory",
- poetry_with_source: "Poetry",
+ command_tester_factory: CommandTesterFactory,
+ poetry_with_source: Poetry,
add_multiple_sources: None,
-) -> "CommandTester":
+) -> CommandTester:
return command_tester_factory("source remove", poetry=poetry_with_source)
def test_source_remove_simple(
- tester: "CommandTester",
- poetry_with_source: "Poetry",
- source_existing: "Source",
- source_one: "Source",
- source_two: "Source",
+ tester: CommandTester,
+ poetry_with_source: Poetry,
+ source_existing: Source,
+ source_one: Source,
+ source_two: Source,
):
tester.execute(f"{source_existing.name}")
assert (
@@ -40,7 +42,7 @@ def test_source_remove_simple(
assert tester.status_code == 0
-def test_source_remove_error(tester: "CommandTester"):
+def test_source_remove_error(tester: CommandTester):
tester.execute("error")
assert tester.io.fetch_error().strip() == "Source with name error was not found."
assert tester.status_code == 1
diff --git a/tests/console/commands/source/test_show.py b/tests/console/commands/source/test_show.py
index b000b2c8db2..78c0c6f7a00 100644
--- a/tests/console/commands/source/test_show.py
+++ b/tests/console/commands/source/test_show.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -13,14 +15,14 @@
@pytest.fixture
def tester(
- command_tester_factory: "CommandTesterFactory",
- poetry_with_source: "Poetry",
+ command_tester_factory: CommandTesterFactory,
+ poetry_with_source: Poetry,
add_multiple_sources: None,
-) -> "CommandTester":
+) -> CommandTester:
return command_tester_factory("source show", poetry=poetry_with_source)
-def test_source_show_simple(tester: "CommandTester"):
+def test_source_show_simple(tester: CommandTester):
tester.execute("")
expected = """\
@@ -46,7 +48,7 @@ def test_source_show_simple(tester: "CommandTester"):
assert tester.status_code == 0
-def test_source_show_one(tester: "CommandTester", source_one: "Source"):
+def test_source_show_one(tester: CommandTester, source_one: Source):
tester.execute(f"{source_one.name}")
expected = """\
@@ -62,9 +64,7 @@ def test_source_show_one(tester: "CommandTester", source_one: "Source"):
assert tester.status_code == 0
-def test_source_show_two(
- tester: "CommandTester", source_one: "Source", source_two: "Source"
-):
+def test_source_show_two(tester: CommandTester, source_one: Source, source_two: Source):
tester.execute(f"{source_one.name} {source_two.name}")
expected = """\
@@ -85,7 +85,7 @@ def test_source_show_two(
assert tester.status_code == 0
-def test_source_show_error(tester: "CommandTester"):
+def test_source_show_error(tester: CommandTester):
tester.execute("error")
assert tester.io.fetch_error().strip() == "No source found with name(s): error"
assert tester.status_code == 1
diff --git a/tests/console/commands/test_about.py b/tests/console/commands/test_about.py
index 70703cff075..bd7eb1869b5 100644
--- a/tests/console/commands/test_about.py
+++ b/tests/console/commands/test_about.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -10,11 +12,11 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("about")
-def test_about(tester: "CommandTester"):
+def test_about(tester: CommandTester):
tester.execute()
expected = """\
Poetry - Package Management for Python
diff --git a/tests/console/commands/test_add.py b/tests/console/commands/test_add.py
index 54232ed6aaa..987739b234e 100644
--- a/tests/console/commands/test_add.py
+++ b/tests/console/commands/test_add.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import sys
from pathlib import Path
@@ -26,19 +28,19 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("add")
@pytest.fixture()
-def old_tester(tester: "CommandTester") -> "CommandTester":
+def old_tester(tester: CommandTester) -> CommandTester:
tester.command.installer.use_executor(False)
return tester
def test_add_no_constraint(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -68,7 +70,7 @@ def test_add_no_constraint(
def test_add_replace_by_constraint(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -115,7 +117,7 @@ def test_add_replace_by_constraint(
def test_add_no_constraint_editable_error(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
content = app.poetry.file.read()["tool"]["poetry"]
@@ -136,7 +138,7 @@ def test_add_no_constraint_editable_error(
def test_add_equal_constraint(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -160,7 +162,7 @@ def test_add_equal_constraint(
def test_add_greater_constraint(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -184,7 +186,7 @@ def test_add_greater_constraint(
def test_add_constraint_with_extras(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
cachy1 = get_package("cachy", "0.1.0")
cachy1.extras = {"msgpack": [get_dependency("msgpack-python")]}
@@ -215,7 +217,7 @@ def test_add_constraint_with_extras(
def test_add_constraint_dependencies(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
cachy2 = get_package("cachy", "0.2.0")
msgpack_dep = get_dependency("msgpack-python", ">=0.5 <0.6")
@@ -245,10 +247,10 @@ def test_add_constraint_dependencies(
def test_add_git_constraint(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- tmp_venv: "VirtualEnv",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ tmp_venv: VirtualEnv,
):
tester.command.set_env(tmp_venv)
@@ -282,10 +284,10 @@ def test_add_git_constraint(
def test_add_git_constraint_with_poetry(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- tmp_venv: "VirtualEnv",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ tmp_venv: VirtualEnv,
):
tester.command.set_env(tmp_venv)
@@ -311,10 +313,10 @@ def test_add_git_constraint_with_poetry(
def test_add_git_constraint_with_extras(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- tmp_venv: "VirtualEnv",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ tmp_venv: VirtualEnv,
):
tester.command.set_env(tmp_venv)
@@ -354,10 +356,10 @@ def test_add_git_constraint_with_extras(
@pytest.mark.parametrize("editable", [False, True])
def test_add_git_ssh_constraint(
editable: bool,
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- tmp_venv: "VirtualEnv",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ tmp_venv: VirtualEnv,
):
tester.command.set_env(tmp_venv)
@@ -400,10 +402,10 @@ def test_add_git_ssh_constraint(
@pytest.mark.parametrize("editable", [False, True])
def test_add_directory_constraint(
editable: bool,
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ mocker: MockerFixture,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__).parent
@@ -442,10 +444,10 @@ def test_add_directory_constraint(
def test_add_directory_with_poetry(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ mocker: MockerFixture,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -473,11 +475,11 @@ def test_add_directory_with_poetry(
def test_add_file_constraint_wheel(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- mocker: "MockerFixture",
- poetry: "Poetry",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ mocker: MockerFixture,
+ poetry: Poetry,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = poetry.file.parent
@@ -512,10 +514,10 @@ def test_add_file_constraint_wheel(
def test_add_file_constraint_sdist(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ mocker: MockerFixture,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -550,7 +552,7 @@ def test_add_file_constraint_sdist(
def test_add_constraint_with_extras_option(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
cachy2 = get_package("cachy", "0.2.0")
cachy2.extras = {"msgpack": [get_dependency("msgpack-python")]}
@@ -589,10 +591,10 @@ def test_add_constraint_with_extras_option(
def test_add_url_constraint_wheel(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ mocker: MockerFixture,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -629,10 +631,10 @@ def test_add_url_constraint_wheel(
def test_add_url_constraint_wheel_with_extras(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ mocker: MockerFixture,
):
repo.add_package(get_package("pendulum", "1.4.4"))
repo.add_package(get_package("cleo", "0.6.5"))
@@ -676,7 +678,7 @@ def test_add_url_constraint_wheel_with_extras(
def test_add_constraint_with_python(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
cachy2 = get_package("cachy", "0.2.0")
@@ -707,10 +709,10 @@ def test_add_constraint_with_python(
def test_add_constraint_with_platform(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- tester: "CommandTester",
- env: "MockEnv",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ tester: CommandTester,
+ env: MockEnv,
):
platform = sys.platform
env._platform = platform
@@ -747,7 +749,7 @@ def test_add_constraint_with_platform(
def test_add_constraint_with_source(
- app: "PoetryTestApplication", poetry: "Poetry", tester: "CommandTester"
+ app: PoetryTestApplication, poetry: Poetry, tester: CommandTester
):
repo = LegacyRepository(name="my-index", url="https://my-index.fake")
repo.add_package(get_package("cachy", "0.2.0"))
@@ -782,7 +784,7 @@ def test_add_constraint_with_source(
def test_add_constraint_with_source_that_does_not_exist(
- app: "PoetryTestApplication", tester: "CommandTester"
+ app: PoetryTestApplication, tester: CommandTester
):
with pytest.raises(ValueError) as e:
tester.execute("foo --source i-dont-exist")
@@ -791,10 +793,10 @@ def test_add_constraint_with_source_that_does_not_exist(
def test_add_constraint_not_found_with_source(
- app: "PoetryTestApplication",
- poetry: "Poetry",
- mocker: "MockerFixture",
- tester: "CommandTester",
+ app: PoetryTestApplication,
+ poetry: Poetry,
+ mocker: MockerFixture,
+ tester: CommandTester,
):
repo = LegacyRepository(name="my-index", url="https://my-index.fake")
mocker.patch.object(repo, "find_packages", return_value=[])
@@ -811,7 +813,7 @@ def test_add_constraint_not_found_with_source(
def test_add_to_section_that_does_not_exist_yet(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -850,7 +852,7 @@ def test_add_to_section_that_does_not_exist_yet(
def test_add_to_dev_section_deprecated(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -885,7 +887,7 @@ def test_add_to_dev_section_deprecated(
def test_add_should_not_select_prereleases(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("pyyaml", "3.13"))
repo.add_package(get_package("pyyaml", "4.2b2"))
@@ -915,7 +917,7 @@ def test_add_should_not_select_prereleases(
def test_add_should_skip_when_adding_existing_package_with_no_constraint(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
content = app.poetry.file.read()
content["tool"]["poetry"]["dependencies"]["foo"] = "^1.0"
@@ -939,7 +941,7 @@ def test_add_should_skip_when_adding_existing_package_with_no_constraint(
def test_add_should_work_when_adding_existing_package_with_latest_constraint(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
content = app.poetry.file.read()
content["tool"]["poetry"]["dependencies"]["foo"] = "^1.0"
@@ -971,7 +973,7 @@ def test_add_should_work_when_adding_existing_package_with_latest_constraint(
def test_add_chooses_prerelease_if_only_prereleases_are_available(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("foo", "1.2.3b0"))
repo.add_package(get_package("foo", "1.2.3b1"))
@@ -995,7 +997,7 @@ def test_add_chooses_prerelease_if_only_prereleases_are_available(
def test_add_prefers_stable_releases(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
repo.add_package(get_package("foo", "1.2.3"))
repo.add_package(get_package("foo", "1.2.4b1"))
@@ -1019,7 +1021,7 @@ def test_add_prefers_stable_releases(
def test_add_with_lock(
- app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester"
+ app: PoetryTestApplication, repo: TestRepository, tester: CommandTester
):
content_hash = app.poetry.locker._get_content_hash()
repo.add_package(get_package("cachy", "0.2.0"))
@@ -1040,10 +1042,10 @@ def test_add_with_lock(
def test_add_no_constraint_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -1074,10 +1076,10 @@ def test_add_no_constraint_old_installer(
def test_add_equal_constraint_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -1102,10 +1104,10 @@ def test_add_equal_constraint_old_installer(
def test_add_greater_constraint_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -1130,10 +1132,10 @@ def test_add_greater_constraint_old_installer(
def test_add_constraint_with_extras_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
cachy1 = get_package("cachy", "0.1.0")
cachy1.extras = {"msgpack": [get_dependency("msgpack-python")]}
@@ -1165,10 +1167,10 @@ def test_add_constraint_with_extras_old_installer(
def test_add_constraint_dependencies_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
cachy2 = get_package("cachy", "0.2.0")
msgpack_dep = get_dependency("msgpack-python", ">=0.5 <0.6")
@@ -1199,10 +1201,10 @@ def test_add_constraint_dependencies_old_installer(
def test_add_git_constraint_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("pendulum", "1.4.4"))
repo.add_package(get_package("cleo", "0.6.5"))
@@ -1235,10 +1237,10 @@ def test_add_git_constraint_old_installer(
def test_add_git_constraint_with_poetry_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("pendulum", "1.4.4"))
@@ -1263,10 +1265,10 @@ def test_add_git_constraint_with_poetry_old_installer(
def test_add_git_constraint_with_extras_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("pendulum", "1.4.4"))
repo.add_package(get_package("cleo", "0.6.5"))
@@ -1303,10 +1305,10 @@ def test_add_git_constraint_with_extras_old_installer(
def test_add_git_ssh_constraint_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("pendulum", "1.4.4"))
repo.add_package(get_package("cleo", "0.6.5"))
@@ -1340,11 +1342,11 @@ def test_add_git_ssh_constraint_old_installer(
def test_add_directory_constraint_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- mocker: "MockerFixture",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ mocker: MockerFixture,
+ old_tester: CommandTester,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -1379,11 +1381,11 @@ def test_add_directory_constraint_old_installer(
def test_add_directory_with_poetry_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- mocker: "MockerFixture",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ mocker: MockerFixture,
+ old_tester: CommandTester,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -1412,11 +1414,11 @@ def test_add_directory_with_poetry_old_installer(
def test_add_file_constraint_wheel_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- mocker: "MockerFixture",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ mocker: MockerFixture,
+ old_tester: CommandTester,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -1452,11 +1454,11 @@ def test_add_file_constraint_wheel_old_installer(
def test_add_file_constraint_sdist_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- mocker: "MockerFixture",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ mocker: MockerFixture,
+ old_tester: CommandTester,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -1492,10 +1494,10 @@ def test_add_file_constraint_sdist_old_installer(
def test_add_constraint_with_extras_option_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
cachy2 = get_package("cachy", "0.2.0")
cachy2.extras = {"msgpack": [get_dependency("msgpack-python")]}
@@ -1535,11 +1537,11 @@ def test_add_constraint_with_extras_option_old_installer(
def test_add_url_constraint_wheel_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- mocker: "MockerFixture",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ mocker: MockerFixture,
+ old_tester: CommandTester,
):
p = mocker.patch("pathlib.Path.cwd")
p.return_value = Path(__file__) / ".."
@@ -1577,10 +1579,10 @@ def test_add_url_constraint_wheel_old_installer(
def test_add_url_constraint_wheel_with_extras_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("pendulum", "1.4.4"))
repo.add_package(get_package("cleo", "0.6.5"))
@@ -1623,10 +1625,10 @@ def test_add_url_constraint_wheel_with_extras_old_installer(
def test_add_constraint_with_python_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
cachy2 = get_package("cachy", "0.2.0")
@@ -1658,11 +1660,11 @@ def test_add_constraint_with_python_old_installer(
def test_add_constraint_with_platform_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- env: "MockEnv",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ env: MockEnv,
+ old_tester: CommandTester,
):
platform = sys.platform
env._platform = platform
@@ -1700,10 +1702,10 @@ def test_add_constraint_with_platform_old_installer(
def test_add_constraint_with_source_old_installer(
- app: "PoetryTestApplication",
- poetry: "Poetry",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ poetry: Poetry,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo = LegacyRepository(name="my-index", url="https://my-index.fake")
repo.add_package(get_package("cachy", "0.2.0"))
@@ -1739,7 +1741,7 @@ def test_add_constraint_with_source_old_installer(
def test_add_constraint_with_source_that_does_not_exist_old_installer(
- app: "PoetryTestApplication", old_tester: "CommandTester"
+ app: PoetryTestApplication, old_tester: CommandTester
):
with pytest.raises(ValueError) as e:
old_tester.execute("foo --source i-dont-exist")
@@ -1748,10 +1750,10 @@ def test_add_constraint_with_source_that_does_not_exist_old_installer(
def test_add_constraint_not_found_with_source_old_installer(
- app: "PoetryTestApplication",
- poetry: "Poetry",
- mocker: "MockerFixture",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ poetry: Poetry,
+ mocker: MockerFixture,
+ old_tester: CommandTester,
):
repo = LegacyRepository(name="my-index", url="https://my-index.fake")
mocker.patch.object(repo, "find_packages", return_value=[])
@@ -1768,10 +1770,10 @@ def test_add_constraint_not_found_with_source_old_installer(
def test_add_to_section_that_does_no_exist_yet_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(get_package("cachy", "0.2.0"))
@@ -1802,10 +1804,10 @@ def test_add_to_section_that_does_no_exist_yet_old_installer(
def test_add_should_not_select_prereleases_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("pyyaml", "3.13"))
repo.add_package(get_package("pyyaml", "4.2b2"))
@@ -1836,10 +1838,10 @@ def test_add_should_not_select_prereleases_old_installer(
def test_add_should_skip_when_adding_existing_package_with_no_constraint_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
content = app.poetry.file.read()
content["tool"]["poetry"]["dependencies"]["foo"] = "^1.0"
@@ -1864,10 +1866,10 @@ def test_add_should_skip_when_adding_existing_package_with_no_constraint_old_ins
def test_add_should_work_when_adding_existing_package_with_latest_constraint_old_installer( # noqa: E501
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
content = app.poetry.file.read()
content["tool"]["poetry"]["dependencies"]["foo"] = "^1.0"
@@ -1899,10 +1901,10 @@ def test_add_should_work_when_adding_existing_package_with_latest_constraint_old
def test_add_chooses_prerelease_if_only_prereleases_are_available_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("foo", "1.2.3b0"))
repo.add_package(get_package("foo", "1.2.3b1"))
@@ -1926,10 +1928,10 @@ def test_add_chooses_prerelease_if_only_prereleases_are_available_old_installer(
def test_add_preferes_stable_releases_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("foo", "1.2.3"))
repo.add_package(get_package("foo", "1.2.4b1"))
@@ -1953,10 +1955,10 @@ def test_add_preferes_stable_releases_old_installer(
def test_add_with_lock_old_installer(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- old_tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ old_tester: CommandTester,
):
repo.add_package(get_package("cachy", "0.2.0"))
@@ -1975,11 +1977,11 @@ def test_add_with_lock_old_installer(
def test_add_keyboard_interrupt_restore_content(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- tester: "CommandTester",
- mocker: "MockerFixture",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ tester: CommandTester,
+ mocker: MockerFixture,
):
mocker.patch(
"poetry.installation.installer.Installer.run", side_effect=KeyboardInterrupt()
@@ -1994,10 +1996,10 @@ def test_add_keyboard_interrupt_restore_content(
def test_dry_run_restore_original_content(
- app: "PoetryTestApplication",
- repo: "TestRepository",
- installer: "NoopInstaller",
- tester: "CommandTester",
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ installer: NoopInstaller,
+ tester: CommandTester,
):
original_content = app.poetry.file.read()
diff --git a/tests/console/commands/test_cache.py b/tests/console/commands/test_cache.py
index 9bf42286bbb..afc590a95bb 100644
--- a/tests/console/commands/test_cache.py
+++ b/tests/console/commands/test_cache.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import uuid
from typing import TYPE_CHECKING
@@ -15,7 +17,7 @@
@pytest.fixture
-def repository_cache_dir(monkeypatch: "MonkeyPatch", tmpdir: "Path") -> "Path":
+def repository_cache_dir(monkeypatch: MonkeyPatch, tmpdir: Path) -> Path:
from pathlib import Path
import poetry.locations
@@ -37,19 +39,19 @@ def repository_two() -> str:
@pytest.fixture
def mock_caches(
- repository_cache_dir: "Path", repository_one: str, repository_two: str
+ repository_cache_dir: Path, repository_one: str, repository_two: str
) -> None:
(repository_cache_dir / repository_one).mkdir()
(repository_cache_dir / repository_two).mkdir()
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("cache list")
def test_cache_list(
- tester: "CommandTester", mock_caches: None, repository_one: str, repository_two: str
+ tester: CommandTester, mock_caches: None, repository_one: str, repository_two: str
):
tester.execute()
@@ -61,7 +63,7 @@ def test_cache_list(
assert tester.io.fetch_output() == expected
-def test_cache_list_empty(tester: "CommandTester", repository_cache_dir: "Path"):
+def test_cache_list_empty(tester: CommandTester, repository_cache_dir: Path):
tester.execute()
expected = """\
diff --git a/tests/console/commands/test_check.py b/tests/console/commands/test_check.py
index d59e26011b4..9c913616876 100644
--- a/tests/console/commands/test_check.py
+++ b/tests/console/commands/test_check.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
@@ -12,11 +14,11 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("check")
-def test_check_valid(tester: "CommandTester"):
+def test_check_valid(tester: CommandTester):
tester.execute()
expected = """\
@@ -26,7 +28,7 @@ def test_check_valid(tester: "CommandTester"):
assert tester.io.fetch_output() == expected
-def test_check_invalid(mocker: "MockerFixture", tester: "CommandTester"):
+def test_check_invalid(mocker: MockerFixture, tester: CommandTester):
mocker.patch(
"poetry.factory.Factory.locate",
return_value=Path(__file__).parent.parent.parent
diff --git a/tests/console/commands/test_config.py b/tests/console/commands/test_config.py
index 9e4bda394c5..4d340ba8b33 100644
--- a/tests/console/commands/test_config.py
+++ b/tests/console/commands/test_config.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import json
import os
@@ -24,12 +26,12 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("config")
def test_show_config_with_local_config_file_empty(
- tester: "CommandTester", mocker: "MockerFixture"
+ tester: CommandTester, mocker: MockerFixture
):
mocker.patch(
"poetry.factory.Factory.create_poetry",
@@ -41,7 +43,7 @@ def test_show_config_with_local_config_file_empty(
def test_list_displays_default_value_if_not_set(
- tester: "CommandTester", config: "Config", config_cache_dir: "Path"
+ tester: CommandTester, config: Config, config_cache_dir: Path
):
tester.execute("--list")
@@ -63,7 +65,7 @@ def test_list_displays_default_value_if_not_set(
def test_list_displays_set_get_setting(
- tester: "CommandTester", config: "Config", config_cache_dir: "Path"
+ tester: CommandTester, config: Config, config_cache_dir: Path
):
tester.execute("virtualenvs.create false")
@@ -87,7 +89,7 @@ def test_list_displays_set_get_setting(
assert tester.io.fetch_output() == expected
-def test_display_single_setting(tester: "CommandTester", config: "Config"):
+def test_display_single_setting(tester: CommandTester, config: Config):
tester.execute("virtualenvs.create")
expected = """true
@@ -97,7 +99,7 @@ def test_display_single_setting(tester: "CommandTester", config: "Config"):
def test_display_single_local_setting(
- command_tester_factory: "CommandTesterFactory", fixture_dir: "FixtureDirGetter"
+ command_tester_factory: CommandTesterFactory, fixture_dir: FixtureDirGetter
):
tester = command_tester_factory(
"config", poetry=Factory().create_poetry(fixture_dir("with_local_config"))
@@ -111,7 +113,7 @@ def test_display_single_local_setting(
def test_list_displays_set_get_local_setting(
- tester: "CommandTester", config: "Config", config_cache_dir: "Path"
+ tester: CommandTester, config: Config, config_cache_dir: Path
):
tester.execute("virtualenvs.create false --local")
@@ -135,9 +137,7 @@ def test_list_displays_set_get_local_setting(
assert tester.io.fetch_output() == expected
-def test_set_pypi_token(
- tester: "CommandTester", auth_config_source: "DictConfigSource"
-):
+def test_set_pypi_token(tester: CommandTester, auth_config_source: DictConfigSource):
tester.execute("pypi-token.pypi mytoken")
tester.execute("--list")
@@ -145,9 +145,9 @@ def test_set_pypi_token(
def test_set_client_cert(
- tester: "CommandTester",
- auth_config_source: "DictConfigSource",
- mocker: "MockerFixture",
+ tester: CommandTester,
+ auth_config_source: DictConfigSource,
+ mocker: MockerFixture,
):
mocker.spy(ConfigSource, "__init__")
@@ -160,9 +160,9 @@ def test_set_client_cert(
def test_set_cert(
- tester: "CommandTester",
- auth_config_source: "DictConfigSource",
- mocker: "MockerFixture",
+ tester: CommandTester,
+ auth_config_source: DictConfigSource,
+ mocker: MockerFixture,
):
mocker.spy(ConfigSource, "__init__")
@@ -172,7 +172,7 @@ def test_set_cert(
def test_config_installer_parallel(
- tester: "CommandTester", command_tester_factory: "CommandTesterFactory"
+ tester: CommandTester, command_tester_factory: CommandTesterFactory
):
tester.execute("--local installer.parallel")
assert tester.io.fetch_output().strip() == "true"
diff --git a/tests/console/commands/test_export.py b/tests/console/commands/test_export.py
index 010dfd10617..c277ffa6b0c 100644
--- a/tests/console/commands/test_export.py
+++ b/tests/console/commands/test_export.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from unittest.mock import ANY
from unittest.mock import Mock
@@ -53,24 +55,24 @@
@pytest.fixture(autouse=True)
-def setup(repo: "TestRepository") -> None:
+def setup(repo: TestRepository) -> None:
repo.add_package(get_package("foo", "1.0.0"))
repo.add_package(get_package("bar", "1.1.0"))
@pytest.fixture
-def poetry(project_factory: "ProjectFactory") -> "Poetry":
+def poetry(project_factory: ProjectFactory) -> Poetry:
return project_factory(name="export", pyproject_content=PYPROJECT_CONTENT)
@pytest.fixture
def tester(
- command_tester_factory: "CommandTesterFactory", poetry: "Poetry"
-) -> "CommandTester":
+ command_tester_factory: CommandTesterFactory, poetry: Poetry
+) -> CommandTester:
return command_tester_factory("export", poetry=poetry)
-def _export_requirements(tester: "CommandTester", poetry: "Poetry") -> None:
+def _export_requirements(tester: CommandTester, poetry: Poetry) -> None:
tester.execute("--format requirements.txt --output requirements.txt")
requirements = poetry.file.parent / "requirements.txt"
@@ -89,7 +91,7 @@ def _export_requirements(tester: "CommandTester", poetry: "Poetry") -> None:
def test_export_exports_requirements_txt_file_locks_if_no_lock_file(
- tester: "CommandTester", poetry: "Poetry"
+ tester: CommandTester, poetry: Poetry
):
assert not poetry.locker.lock.exists()
_export_requirements(tester, poetry)
@@ -97,18 +99,18 @@ def test_export_exports_requirements_txt_file_locks_if_no_lock_file(
def test_export_exports_requirements_txt_uses_lock_file(
- tester: "CommandTester", poetry: "Poetry", do_lock: None
+ tester: CommandTester, poetry: Poetry, do_lock: None
):
_export_requirements(tester, poetry)
assert "The lock file does not exist. Locking." not in tester.io.fetch_error()
-def test_export_fails_on_invalid_format(tester: "CommandTester", do_lock: None):
+def test_export_fails_on_invalid_format(tester: CommandTester, do_lock: None):
with pytest.raises(ValueError):
tester.execute("--format invalid")
-def test_export_prints_to_stdout_by_default(tester: "CommandTester", do_lock: None):
+def test_export_prints_to_stdout_by_default(tester: CommandTester, do_lock: None):
tester.execute("--format requirements.txt")
expected = """\
foo==1.0.0
@@ -117,7 +119,7 @@ def test_export_prints_to_stdout_by_default(tester: "CommandTester", do_lock: No
def test_export_uses_requirements_txt_format_by_default(
- tester: "CommandTester", do_lock: None
+ tester: CommandTester, do_lock: None
):
tester.execute()
expected = """\
@@ -126,7 +128,7 @@ def test_export_uses_requirements_txt_format_by_default(
assert tester.io.fetch_output() == expected
-def test_export_includes_extras_by_flag(tester: "CommandTester", do_lock: None):
+def test_export_includes_extras_by_flag(tester: CommandTester, do_lock: None):
tester.execute("--format requirements.txt --extras feature_bar")
expected = """\
bar==1.1.0
@@ -136,7 +138,7 @@ def test_export_includes_extras_by_flag(tester: "CommandTester", do_lock: None):
def test_export_with_urls(
- monkeypatch: "MonkeyPatch", tester: "CommandTester", poetry: "Poetry"
+ monkeypatch: MonkeyPatch, tester: CommandTester, poetry: Poetry
):
"""
We are just validating that the option gets passed. The option itself is tested in
diff --git a/tests/console/commands/test_init.py b/tests/console/commands/test_init.py
index 4e11f393a29..0aee48f854f 100644
--- a/tests/console/commands/test_init.py
+++ b/tests/console/commands/test_init.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import shutil
import sys
@@ -5,7 +7,6 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Iterator
-from typing import List
import pytest
@@ -40,7 +41,7 @@ def source_dir(tmp_path: Path) -> Iterator[Path]:
@pytest.fixture
-def patches(mocker: "MockerFixture", source_dir: Path, repo: "TestRepository") -> None:
+def patches(mocker: MockerFixture, source_dir: Path, repo: TestRepository) -> None:
mocker.patch("pathlib.Path.cwd", return_value=source_dir)
mocker.patch(
"poetry.console.commands.init.InitCommand._get_pool", return_value=Pool([repo])
@@ -97,9 +98,9 @@ def test_basic_interactive(
def test_noninteractive(
app: PoetryTestApplication,
- mocker: "MockerFixture",
- poetry: "Poetry",
- repo: "TestRepository",
+ mocker: MockerFixture,
+ poetry: Poetry,
+ repo: TestRepository,
tmp_path: Path,
):
command = app.find("init")
@@ -123,7 +124,7 @@ def test_noninteractive(
assert 'pytest = "^3.6.0"' in toml_content
-def test_interactive_with_dependencies(tester: CommandTester, repo: "TestRepository"):
+def test_interactive_with_dependencies(tester: CommandTester, repo: TestRepository):
repo.add_package(get_package("django-pendulum", "0.1.6-pre4"))
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pytest", "3.6.0"))
@@ -205,9 +206,7 @@ def test_empty_license(tester: CommandTester):
assert expected in tester.io.fetch_output()
-def test_interactive_with_git_dependencies(
- tester: CommandTester, repo: "TestRepository"
-):
+def test_interactive_with_git_dependencies(tester: CommandTester, repo: TestRepository):
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pytest", "3.6.0"))
@@ -251,7 +250,7 @@ def test_interactive_with_git_dependencies(
assert expected in tester.io.fetch_output()
-_generate_choice_list_packages_params: List[List["Package"]] = [
+_generate_choice_list_packages_params: list[list[Package]] = [
[
get_package("flask-blacklist", "1.0.0"),
get_package("Flask-Shelve", "1.0.0"),
@@ -276,7 +275,7 @@ def test_interactive_with_git_dependencies(
@pytest.fixture(params=_generate_choice_list_packages_params)
-def _generate_choice_list_packages(request: "FixtureRequest") -> List["Package"]:
+def _generate_choice_list_packages(request: FixtureRequest) -> list[Package]:
return request.param
@@ -284,7 +283,7 @@ def _generate_choice_list_packages(request: "FixtureRequest") -> List["Package"]
def test_generate_choice_list(
tester: CommandTester,
package_name: str,
- _generate_choice_list_packages: List["Package"],
+ _generate_choice_list_packages: list[Package],
):
init_command = tester.command
@@ -297,7 +296,7 @@ def test_generate_choice_list(
def test_interactive_with_git_dependencies_with_reference(
- tester: CommandTester, repo: "TestRepository"
+ tester: CommandTester, repo: TestRepository
):
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pytest", "3.6.0"))
@@ -343,7 +342,7 @@ def test_interactive_with_git_dependencies_with_reference(
def test_interactive_with_git_dependencies_and_other_name(
- tester: CommandTester, repo: "TestRepository"
+ tester: CommandTester, repo: TestRepository
):
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pytest", "3.6.0"))
@@ -390,9 +389,9 @@ def test_interactive_with_git_dependencies_and_other_name(
def test_interactive_with_directory_dependency(
tester: CommandTester,
- repo: "TestRepository",
+ repo: TestRepository,
source_dir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pytest", "3.6.0"))
@@ -441,9 +440,9 @@ def test_interactive_with_directory_dependency(
def test_interactive_with_directory_dependency_and_other_name(
tester: CommandTester,
- repo: "TestRepository",
+ repo: TestRepository,
source_dir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pytest", "3.6.0"))
@@ -493,9 +492,9 @@ def test_interactive_with_directory_dependency_and_other_name(
def test_interactive_with_file_dependency(
tester: CommandTester,
- repo: "TestRepository",
+ repo: TestRepository,
source_dir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pytest", "3.6.0"))
@@ -573,7 +572,7 @@ def test_python_option(tester: CommandTester):
assert expected in tester.io.fetch_output()
-def test_predefined_dependency(tester: CommandTester, repo: "TestRepository"):
+def test_predefined_dependency(tester: CommandTester, repo: TestRepository):
repo.add_package(get_package("pendulum", "2.0.0"))
inputs = [
@@ -608,7 +607,7 @@ def test_predefined_dependency(tester: CommandTester, repo: "TestRepository"):
def test_predefined_and_interactive_dependencies(
- tester: CommandTester, repo: "TestRepository"
+ tester: CommandTester, repo: TestRepository
):
repo.add_package(get_package("pendulum", "2.0.0"))
repo.add_package(get_package("pyramid", "1.10"))
@@ -650,7 +649,7 @@ def test_predefined_and_interactive_dependencies(
assert 'pyramid = "^1.10"' in output
-def test_predefined_dev_dependency(tester: CommandTester, repo: "TestRepository"):
+def test_predefined_dev_dependency(tester: CommandTester, repo: TestRepository):
repo.add_package(get_package("pytest", "3.6.0"))
inputs = [
@@ -688,7 +687,7 @@ def test_predefined_dev_dependency(tester: CommandTester, repo: "TestRepository"
def test_predefined_and_interactive_dev_dependencies(
- tester: CommandTester, repo: "TestRepository"
+ tester: CommandTester, repo: TestRepository
):
repo.add_package(get_package("pytest", "3.6.0"))
repo.add_package(get_package("pytest-requests", "0.2.0"))
@@ -764,7 +763,7 @@ def test_init_non_interactive_existing_pyproject_add_dependency(
tester: CommandTester,
source_dir: Path,
init_basic_inputs: str,
- repo: "TestRepository",
+ repo: TestRepository,
):
pyproject_file = source_dir / "pyproject.toml"
existing_section = """
diff --git a/tests/console/commands/test_install.py b/tests/console/commands/test_install.py
index 485207d5274..c06f1a9e342 100644
--- a/tests/console/commands/test_install.py
+++ b/tests/console/commands/test_install.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -11,12 +13,12 @@
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("install")
def test_group_options_are_passed_to_the_installer(
- tester: "CommandTester", mocker: "MockerFixture"
+ tester: CommandTester, mocker: MockerFixture
):
"""
Group options are passed properly to the installer.
@@ -31,7 +33,7 @@ def test_group_options_are_passed_to_the_installer(
def test_sync_option_is_passed_to_the_installer(
- tester: "CommandTester", mocker: "MockerFixture"
+ tester: CommandTester, mocker: MockerFixture
):
"""
The --sync option is passed properly to the installer.
diff --git a/tests/console/commands/test_lock.py b/tests/console/commands/test_lock.py
index e7a49b64bc5..f12837d6bc3 100644
--- a/tests/console/commands/test_lock.py
+++ b/tests/console/commands/test_lock.py
@@ -1,6 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Type
import pytest
@@ -26,15 +27,15 @@ def source_dir(tmp_path: Path) -> Path:
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("lock")
def _project_factory(
fixture_name: str,
- project_factory: "ProjectFactory",
- fixture_dir: "FixtureDirGetter",
-) -> "Poetry":
+ project_factory: ProjectFactory,
+ fixture_dir: FixtureDirGetter,
+) -> Poetry:
source = fixture_dir(fixture_name)
pyproject_content = (source / "pyproject.toml").read_text(encoding="utf-8")
poetry_lock_content = (source / "poetry.lock").read_text(encoding="utf-8")
@@ -47,29 +48,29 @@ def _project_factory(
@pytest.fixture
def poetry_with_outdated_lockfile(
- project_factory: "ProjectFactory", fixture_dir: "FixtureDirGetter"
-) -> "Poetry":
+ project_factory: ProjectFactory, fixture_dir: FixtureDirGetter
+) -> Poetry:
return _project_factory("outdated_lock", project_factory, fixture_dir)
@pytest.fixture
def poetry_with_up_to_date_lockfile(
- project_factory: "ProjectFactory", fixture_dir: "FixtureDirGetter"
-) -> "Poetry":
+ project_factory: ProjectFactory, fixture_dir: FixtureDirGetter
+) -> Poetry:
return _project_factory("up_to_date_lock", project_factory, fixture_dir)
@pytest.fixture
def poetry_with_old_lockfile(
- project_factory: "ProjectFactory", fixture_dir: "FixtureDirGetter"
-) -> "Poetry":
+ project_factory: ProjectFactory, fixture_dir: FixtureDirGetter
+) -> Poetry:
return _project_factory("old_lock", project_factory, fixture_dir)
def test_lock_check_outdated(
- command_tester_factory: "CommandTesterFactory",
- poetry_with_outdated_lockfile: "Poetry",
- http: Type["httpretty.httpretty"],
+ command_tester_factory: CommandTesterFactory,
+ poetry_with_outdated_lockfile: Poetry,
+ http: type[httpretty.httpretty],
):
http.disable()
@@ -93,9 +94,9 @@ def test_lock_check_outdated(
def test_lock_check_up_to_date(
- command_tester_factory: "CommandTesterFactory",
- poetry_with_up_to_date_lockfile: "Poetry",
- http: Type["httpretty.httpretty"],
+ command_tester_factory: CommandTesterFactory,
+ poetry_with_up_to_date_lockfile: Poetry,
+ http: type[httpretty.httpretty],
):
http.disable()
@@ -115,9 +116,9 @@ def test_lock_check_up_to_date(
def test_lock_no_update(
- command_tester_factory: "CommandTesterFactory",
- poetry_with_old_lockfile: "Poetry",
- repo: "TestRepository",
+ command_tester_factory: CommandTesterFactory,
+ poetry_with_old_lockfile: Poetry,
+ repo: TestRepository,
):
repo.add_package(get_package("sampleproject", "1.3.1"))
repo.add_package(get_package("sampleproject", "2.0.0"))
diff --git a/tests/console/commands/test_new.py b/tests/console/commands/test_new.py
index dd6d4ebefef..7af8d6f0db7 100644
--- a/tests/console/commands/test_new.py
+++ b/tests/console/commands/test_new.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import List
-from typing import Optional
import pytest
@@ -16,13 +16,13 @@
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("new")
def verify_project_directory(
- path: Path, package_name: str, package_path: str, include_from: Optional[str] = None
-) -> "Poetry":
+ path: Path, package_name: str, package_path: str, include_from: str | None = None
+) -> Poetry:
package_path = Path(package_path)
assert path.is_dir()
@@ -143,12 +143,12 @@ def verify_project_directory(
],
)
def test_command_new(
- options: List[str],
+ options: list[str],
directory: str,
package_name: str,
package_path: str,
- include_from: Optional[str],
- tester: "CommandTester",
+ include_from: str | None,
+ tester: CommandTester,
tmp_dir: str,
):
path = Path(tmp_dir) / directory
@@ -158,9 +158,7 @@ def test_command_new(
@pytest.mark.parametrize(("fmt",), [(None,), ("md",), ("rst",)])
-def test_command_new_with_readme(
- fmt: Optional[str], tester: "CommandTester", tmp_dir: str
-):
+def test_command_new_with_readme(fmt: str | None, tester: CommandTester, tmp_dir: str):
package = "package"
path = Path(tmp_dir) / package
options = [path.as_posix()]
diff --git a/tests/console/commands/test_publish.py b/tests/console/commands/test_publish.py
index 55e78a45b13..897d327cef2 100644
--- a/tests/console/commands/test_publish.py
+++ b/tests/console/commands/test_publish.py
@@ -1,7 +1,8 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Type
import pytest
import requests
@@ -19,9 +20,9 @@
def test_publish_returns_non_zero_code_for_upload_errors(
- app: "PoetryTestApplication",
- app_tester: "ApplicationTester",
- http: Type["httpretty.httpretty"],
+ app: PoetryTestApplication,
+ app_tester: ApplicationTester,
+ http: type[httpretty.httpretty],
):
http.register_uri(
http.POST, "https://upload.pypi.org/legacy/", status=400, body="Bad Request"
@@ -46,9 +47,9 @@ def test_publish_returns_non_zero_code_for_upload_errors(
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")
def test_publish_returns_non_zero_code_for_connection_errors(
- app: "PoetryTestApplication",
- app_tester: "ApplicationTester",
- http: Type["httpretty.httpretty"],
+ app: PoetryTestApplication,
+ app_tester: ApplicationTester,
+ http: type[httpretty.httpretty],
):
def request_callback(*_: Any, **__: Any) -> None:
raise requests.ConnectionError()
@@ -66,7 +67,7 @@ def request_callback(*_: Any, **__: Any) -> None:
assert expected in app_tester.io.fetch_error()
-def test_publish_with_cert(app_tester: "ApplicationTester", mocker: "MockerFixture"):
+def test_publish_with_cert(app_tester: ApplicationTester, mocker: MockerFixture):
publisher_publish = mocker.patch("poetry.publishing.Publisher.publish")
app_tester.execute("publish --cert path/to/ca.pem")
@@ -76,9 +77,7 @@ def test_publish_with_cert(app_tester: "ApplicationTester", mocker: "MockerFixtu
] == publisher_publish.call_args
-def test_publish_with_client_cert(
- app_tester: "ApplicationTester", mocker: "MockerFixture"
-):
+def test_publish_with_client_cert(app_tester: ApplicationTester, mocker: MockerFixture):
publisher_publish = mocker.patch("poetry.publishing.Publisher.publish")
app_tester.execute("publish --client-cert path/to/client.pem")
@@ -88,7 +87,7 @@ def test_publish_with_client_cert(
def test_publish_dry_run(
- app_tester: "ApplicationTester", http: Type["httpretty.httpretty"]
+ app_tester: ApplicationTester, http: type[httpretty.httpretty]
):
http.register_uri(
http.POST, "https://upload.pypi.org/legacy/", status=403, body="Forbidden"
diff --git a/tests/console/commands/test_remove.py b/tests/console/commands/test_remove.py
index 332cafb5886..85d7f2a4ddc 100644
--- a/tests/console/commands/test_remove.py
+++ b/tests/console/commands/test_remove.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -19,16 +21,16 @@
@pytest.fixture()
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("remove")
def test_remove_without_specific_group_removes_from_all_groups(
- tester: "CommandTester",
- app: "PoetryTestApplication",
- repo: "TestRepository",
- command_tester_factory: "CommandTesterFactory",
- installed: "Repository",
+ tester: CommandTester,
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ command_tester_factory: CommandTesterFactory,
+ installed: Repository,
):
"""
Removing without specifying a group removes packages from all groups.
@@ -79,11 +81,11 @@ def test_remove_without_specific_group_removes_from_all_groups(
def test_remove_without_specific_group_removes_from_specific_groups(
- tester: "CommandTester",
- app: "PoetryTestApplication",
- repo: "TestRepository",
- command_tester_factory: "CommandTesterFactory",
- installed: "Repository",
+ tester: CommandTester,
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ command_tester_factory: CommandTesterFactory,
+ installed: Repository,
):
"""
Removing with a specific group given removes packages only from this group.
@@ -134,11 +136,11 @@ def test_remove_without_specific_group_removes_from_specific_groups(
def test_remove_does_not_live_empty_groups(
- tester: "CommandTester",
- app: "PoetryTestApplication",
- repo: "TestRepository",
- command_tester_factory: "CommandTesterFactory",
- installed: "Repository",
+ tester: CommandTester,
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ command_tester_factory: CommandTesterFactory,
+ installed: Repository,
):
"""
Empty groups are automatically discarded after package removal.
@@ -182,11 +184,11 @@ def test_remove_does_not_live_empty_groups(
def test_remove_command_should_not_write_changes_upon_installer_errors(
- tester: "CommandTester",
- app: "PoetryTestApplication",
- repo: "TestRepository",
- command_tester_factory: "CommandTesterFactory",
- mocker: "MockerFixture",
+ tester: CommandTester,
+ app: PoetryTestApplication,
+ repo: TestRepository,
+ command_tester_factory: CommandTesterFactory,
+ mocker: MockerFixture,
):
repo.add_package(Package("foo", "2.0.0"))
diff --git a/tests/console/commands/test_run.py b/tests/console/commands/test_run.py
index 1f062984d68..9edfcbfefbf 100644
--- a/tests/console/commands/test_run.py
+++ b/tests/console/commands/test_run.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -13,22 +15,22 @@
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("run")
@pytest.fixture(autouse=True)
-def patches(mocker: "MockerFixture", env: "MockEnv") -> None:
+def patches(mocker: MockerFixture, env: MockEnv) -> None:
mocker.patch("poetry.utils.env.EnvManager.get", return_value=env)
-def test_run_passes_all_args(app_tester: "ApplicationTester", env: "MockEnv"):
+def test_run_passes_all_args(app_tester: ApplicationTester, env: MockEnv):
app_tester.execute("run python -V")
assert [["python", "-V"]] == env.executed
def test_run_keeps_options_passed_before_command(
- app_tester: "ApplicationTester", env: "MockEnv"
+ app_tester: ApplicationTester, env: MockEnv
):
app_tester.execute("-V --no-ansi run python", decorated=True)
diff --git a/tests/console/commands/test_search.py b/tests/console/commands/test_search.py
index 6219f5a9e4a..47aa4d06316 100644
--- a/tests/console/commands/test_search.py
+++ b/tests/console/commands/test_search.py
@@ -1,6 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Type
import pytest
@@ -19,17 +20,17 @@
@pytest.fixture(autouse=True)
-def mock_search_http_response(http: Type["httpretty.httpretty"]) -> None:
+def mock_search_http_response(http: type[httpretty.httpretty]) -> None:
with FIXTURES_DIRECTORY.joinpath("search.html").open(encoding="utf-8") as f:
http.register_uri("GET", "https://pypi.org/search", f.read())
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("search")
-def test_search(tester: "CommandTester", http: Type["httpretty.httpretty"]):
+def test_search(tester: CommandTester, http: type[httpretty.httpretty]):
tester.execute("sqlalchemy")
expected = """
diff --git a/tests/console/commands/test_show.py b/tests/console/commands/test_show.py
index d5604b86cb1..db9034173d5 100644
--- a/tests/console/commands/test_show.py
+++ b/tests/console/commands/test_show.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -18,12 +20,12 @@
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("show")
def test_show_basic_with_installed_packages(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -100,7 +102,7 @@ def test_show_basic_with_installed_packages(
def test_show_basic_with_installed_packages_single(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
@@ -142,7 +144,7 @@ def test_show_basic_with_installed_packages_single(
def test_show_basic_with_not_installed_packages_non_decorated(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -198,7 +200,7 @@ def test_show_basic_with_not_installed_packages_non_decorated(
def test_show_basic_with_not_installed_packages_decorated(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -254,10 +256,10 @@ def test_show_basic_with_not_installed_packages_decorated(
def test_show_latest_non_decorated(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -324,10 +326,10 @@ def test_show_latest_non_decorated(
def test_show_latest_decorated(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -396,10 +398,10 @@ def test_show_latest_decorated(
def test_show_outdated(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -462,10 +464,10 @@ def test_show_outdated(
def test_show_outdated_with_only_up_to_date_packages(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
cachy_020 = get_package("cachy", "0.2.0")
cachy_020.description = "Cachy package"
@@ -504,10 +506,10 @@ def test_show_outdated_with_only_up_to_date_packages(
def test_show_outdated_has_prerelease_but_not_allowed(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -575,10 +577,10 @@ def test_show_outdated_has_prerelease_but_not_allowed(
def test_show_outdated_has_prerelease_and_allowed(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
poetry.package.add_dependency(
Factory.create_dependency(
@@ -650,10 +652,10 @@ def test_show_outdated_has_prerelease_and_allowed(
def test_show_outdated_formatting(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -721,10 +723,10 @@ def test_show_outdated_formatting(
@pytest.mark.parametrize("project_directory", ["project_with_local_dependencies"])
def test_show_outdated_local_dependencies(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
cachy_010 = get_package("cachy", "0.1.0")
cachy_010.description = "Cachy package"
@@ -837,10 +839,10 @@ def test_show_outdated_local_dependencies(
@pytest.mark.parametrize("project_directory", ["project_with_git_dev_dependency"])
def test_show_outdated_git_dev_dependency(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
cachy_010 = get_package("cachy", "0.1.0")
cachy_010.description = "Cachy package"
@@ -939,10 +941,10 @@ def test_show_outdated_git_dev_dependency(
@pytest.mark.parametrize("project_directory", ["project_with_git_dev_dependency"])
def test_show_outdated_no_dev_git_dev_dependency(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
cachy_010 = get_package("cachy", "0.1.0")
cachy_010.description = "Cachy package"
@@ -1036,10 +1038,10 @@ def test_show_outdated_no_dev_git_dev_dependency(
def test_show_hides_incompatible_package(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
poetry.package.add_dependency(
Factory.create_dependency("cachy", {"version": "^0.1.0", "python": "< 2.0"})
@@ -1097,10 +1099,10 @@ def test_show_hides_incompatible_package(
def test_show_all_shows_incompatible_package(
- tester: "CommandTester",
- poetry: "Poetry",
- installed: "Repository",
- repo: "TestRepository",
+ tester: CommandTester,
+ poetry: Poetry,
+ installed: Repository,
+ repo: TestRepository,
):
cachy_010 = get_package("cachy", "0.1.0")
cachy_010.description = "Cachy package"
@@ -1155,7 +1157,7 @@ def test_show_all_shows_incompatible_package(
def test_show_non_dev_with_basic_installed_packages(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -1231,7 +1233,7 @@ def test_show_non_dev_with_basic_installed_packages(
def test_show_with_group_only(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -1306,7 +1308,7 @@ def test_show_with_group_only(
def test_show_with_optional_group(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.1.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "^2.0.0"))
@@ -1391,7 +1393,7 @@ def test_show_with_optional_group(
assert tester.io.fetch_output() == expected
-def test_show_tree(tester: "CommandTester", poetry: "Poetry", installed: "Repository"):
+def test_show_tree(tester: CommandTester, poetry: Poetry, installed: Repository):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.2.0"))
cachy2 = get_package("cachy", "0.2.0")
@@ -1443,9 +1445,7 @@ def test_show_tree(tester: "CommandTester", poetry: "Poetry", installed: "Reposi
assert tester.io.fetch_output() == expected
-def test_show_tree_no_dev(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
-):
+def test_show_tree_no_dev(tester: CommandTester, poetry: Poetry, installed: Repository):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.2.0"))
poetry.package.add_dependency(
Factory.create_dependency("pytest", "^6.1.0", groups=["dev"])
@@ -1513,7 +1513,7 @@ def test_show_tree_no_dev(
def test_show_required_by_deps(
- tester: "CommandTester", poetry: "Poetry", installed: "Repository"
+ tester: CommandTester, poetry: Poetry, installed: Repository
):
poetry.package.add_dependency(Factory.create_dependency("cachy", "^0.2.0"))
poetry.package.add_dependency(Factory.create_dependency("pendulum", "2.0.0"))
diff --git a/tests/console/commands/test_version.py b/tests/console/commands/test_version.py
index 581d66d3f34..b73c92a4fc5 100644
--- a/tests/console/commands/test_version.py
+++ b/tests/console/commands/test_version.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -17,7 +19,7 @@ def command() -> VersionCommand:
@pytest.fixture
-def tester(command_tester_factory: "CommandTesterFactory") -> "CommandTester":
+def tester(command_tester_factory: CommandTesterFactory) -> CommandTester:
return command_tester_factory("version")
@@ -53,21 +55,21 @@ def test_increment_version(
assert command.increment_version(version, rule).text == expected
-def test_version_show(tester: "CommandTester"):
+def test_version_show(tester: CommandTester):
tester.execute()
assert tester.io.fetch_output() == "simple-project 1.2.3\n"
-def test_short_version_show(tester: "CommandTester"):
+def test_short_version_show(tester: CommandTester):
tester.execute("--short")
assert tester.io.fetch_output() == "1.2.3\n"
-def test_version_update(tester: "CommandTester"):
+def test_version_update(tester: CommandTester):
tester.execute("2.0.0")
assert tester.io.fetch_output() == "Bumping version from 1.2.3 to 2.0.0\n"
-def test_short_version_update(tester: "CommandTester"):
+def test_short_version_update(tester: CommandTester):
tester.execute("--short 2.0.0")
assert tester.io.fetch_output() == "2.0.0\n"
diff --git a/tests/console/conftest.py b/tests/console/conftest.py
index d5a6cfc123e..c492629d5a2 100644
--- a/tests/console/conftest.py
+++ b/tests/console/conftest.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
from pathlib import Path
@@ -42,10 +44,10 @@ def env(tmp_dir: str) -> MockEnv:
@pytest.fixture(autouse=True)
def setup(
- mocker: "MockerFixture",
+ mocker: MockerFixture,
installer: NoopInstaller,
- installed: "Repository",
- config: "Config",
+ installed: Repository,
+ config: Config,
env: MockEnv,
) -> Iterator[None]:
# Set Installer's installer
@@ -91,9 +93,7 @@ def project_directory() -> str:
@pytest.fixture
-def poetry(
- repo: "TestRepository", project_directory: str, config: "Config"
-) -> "Poetry":
+def poetry(repo: TestRepository, project_directory: str, config: Config) -> Poetry:
p = Factory().create_poetry(
Path(__file__).parent.parent / "fixtures" / project_directory
)
@@ -115,7 +115,7 @@ def poetry(
@pytest.fixture
-def app(poetry: "Poetry") -> PoetryTestApplication:
+def app(poetry: Poetry) -> PoetryTestApplication:
app_ = PoetryTestApplication(poetry)
return app_
@@ -127,10 +127,10 @@ def app_tester(app: PoetryTestApplication) -> ApplicationTester:
@pytest.fixture
-def new_installer_disabled(config: "Config") -> None:
+def new_installer_disabled(config: Config) -> None:
config.merge({"experimental": {"new-installer": False}})
@pytest.fixture()
-def executor(poetry: "Poetry", config: "Config", env: MockEnv) -> TestExecutor:
+def executor(poetry: Poetry, config: Config, env: MockEnv) -> TestExecutor:
return TestExecutor(env, poetry.pool, config, NullIO())
diff --git a/tests/console/test_application.py b/tests/console/test_application.py
index 008ec98bafa..e528f4b6e08 100644
--- a/tests/console/test_application.py
+++ b/tests/console/test_application.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import re
from typing import TYPE_CHECKING
@@ -30,7 +32,7 @@ def activate(self, application: Application) -> None:
application.command_loader.register_factory("foo", lambda: FooCommand())
-def test_application_with_plugins(mocker: "MockerFixture"):
+def test_application_with_plugins(mocker: MockerFixture):
mocker.patch(
"entrypoints.get_group_all",
return_value=[
@@ -49,7 +51,7 @@ def test_application_with_plugins(mocker: "MockerFixture"):
assert tester.status_code == 0
-def test_application_with_plugins_disabled(mocker: "MockerFixture"):
+def test_application_with_plugins_disabled(mocker: MockerFixture):
mocker.patch(
"entrypoints.get_group_all",
return_value=[
@@ -68,7 +70,7 @@ def test_application_with_plugins_disabled(mocker: "MockerFixture"):
assert tester.status_code == 0
-def test_application_execute_plugin_command(mocker: "MockerFixture"):
+def test_application_execute_plugin_command(mocker: MockerFixture):
mocker.patch(
"entrypoints.get_group_all",
return_value=[
@@ -88,7 +90,7 @@ def test_application_execute_plugin_command(mocker: "MockerFixture"):
def test_application_execute_plugin_command_with_plugins_disabled(
- mocker: "MockerFixture",
+ mocker: MockerFixture,
):
mocker.patch(
"entrypoints.get_group_all",
diff --git a/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py b/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py
index cfce0806c30..7cf236bd15d 100644
--- a/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py
+++ b/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py
@@ -1,5 +1,8 @@
+from __future__ import annotations
+
from distutils.core import setup
+
packages = ["project_with_extras"]
package_data = {"": ["*"]}
diff --git a/tests/fixtures/excluded_subpackage/example/__init__.py b/tests/fixtures/excluded_subpackage/example/__init__.py
index 3dc1f76bc69..4e562f46413 100644
--- a/tests/fixtures/excluded_subpackage/example/__init__.py
+++ b/tests/fixtures/excluded_subpackage/example/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "0.1.0"
diff --git a/tests/fixtures/excluded_subpackage/example/test/excluded.py b/tests/fixtures/excluded_subpackage/example/test/excluded.py
index 08a62eea9b3..de77b168690 100644
--- a/tests/fixtures/excluded_subpackage/example/test/excluded.py
+++ b/tests/fixtures/excluded_subpackage/example/test/excluded.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from tests.fixtures.excluded_subpackage.example import __version__
diff --git a/tests/fixtures/git/github.com/demo/demo/demo/__init__.py b/tests/fixtures/git/github.com/demo/demo/demo/__init__.py
index 10aa336ce07..54887185a48 100644
--- a/tests/fixtures/git/github.com/demo/demo/demo/__init__.py
+++ b/tests/fixtures/git/github.com/demo/demo/demo/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "1.2.3"
diff --git a/tests/fixtures/git/github.com/demo/demo/setup.py b/tests/fixtures/git/github.com/demo/demo/setup.py
index b6f6d0c1f8c..7a4d0142f6e 100644
--- a/tests/fixtures/git/github.com/demo/demo/setup.py
+++ b/tests/fixtures/git/github.com/demo/demo/setup.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from setuptools import setup
diff --git a/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/__init__.py b/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/__init__.py
index 5284146ebf2..77e038d7b25 100644
--- a/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/__init__.py
+++ b/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__import__("pkg_resources").declare_namespace(__name__)
diff --git a/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/one/__init__.py b/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/one/__init__.py
index 1ac9243c76f..29fc816886e 100644
--- a/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/one/__init__.py
+++ b/tests/fixtures/git/github.com/demo/namespace-package-one/namespace_package/one/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
name = "one"
diff --git a/tests/fixtures/git/github.com/demo/namespace-package-one/setup.py b/tests/fixtures/git/github.com/demo/namespace-package-one/setup.py
index 871fae6cf69..b869dbc87af 100644
--- a/tests/fixtures/git/github.com/demo/namespace-package-one/setup.py
+++ b/tests/fixtures/git/github.com/demo/namespace-package-one/setup.py
@@ -1,4 +1,7 @@
-from setuptools import setup, find_packages
+from __future__ import annotations
+
+from setuptools import find_packages
+from setuptools import setup
setup(
diff --git a/tests/fixtures/git/github.com/demo/no-dependencies/demo/__init__.py b/tests/fixtures/git/github.com/demo/no-dependencies/demo/__init__.py
index 10aa336ce07..54887185a48 100644
--- a/tests/fixtures/git/github.com/demo/no-dependencies/demo/__init__.py
+++ b/tests/fixtures/git/github.com/demo/no-dependencies/demo/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "1.2.3"
diff --git a/tests/fixtures/git/github.com/demo/no-dependencies/setup.py b/tests/fixtures/git/github.com/demo/no-dependencies/setup.py
index 099c69cf976..60da31e88e4 100644
--- a/tests/fixtures/git/github.com/demo/no-dependencies/setup.py
+++ b/tests/fixtures/git/github.com/demo/no-dependencies/setup.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from setuptools import setup
diff --git a/tests/fixtures/git/github.com/demo/no-version/demo/__init__.py b/tests/fixtures/git/github.com/demo/no-version/demo/__init__.py
index 10aa336ce07..54887185a48 100644
--- a/tests/fixtures/git/github.com/demo/no-version/demo/__init__.py
+++ b/tests/fixtures/git/github.com/demo/no-version/demo/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "1.2.3"
diff --git a/tests/fixtures/git/github.com/demo/no-version/setup.py b/tests/fixtures/git/github.com/demo/no-version/setup.py
index d14b308cb23..e85c711c115 100644
--- a/tests/fixtures/git/github.com/demo/no-version/setup.py
+++ b/tests/fixtures/git/github.com/demo/no-version/setup.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import ast
import os
diff --git a/tests/fixtures/git/github.com/demo/non-canonical-name/demo/__init__.py b/tests/fixtures/git/github.com/demo/non-canonical-name/demo/__init__.py
index 10aa336ce07..54887185a48 100644
--- a/tests/fixtures/git/github.com/demo/non-canonical-name/demo/__init__.py
+++ b/tests/fixtures/git/github.com/demo/non-canonical-name/demo/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "1.2.3"
diff --git a/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py b/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py
index 8004332d6d9..f2688f6e020 100644
--- a/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py
+++ b/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from setuptools import setup
diff --git a/tests/fixtures/project_with_setup/setup.py b/tests/fixtures/project_with_setup/setup.py
index c329347f9bb..c4b84259192 100644
--- a/tests/fixtures/project_with_setup/setup.py
+++ b/tests/fixtures/project_with_setup/setup.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from setuptools import setup
diff --git a/tests/fixtures/with-include/package_with_include/__init__.py b/tests/fixtures/with-include/package_with_include/__init__.py
index 10aa336ce07..54887185a48 100644
--- a/tests/fixtures/with-include/package_with_include/__init__.py
+++ b/tests/fixtures/with-include/package_with_include/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "1.2.3"
diff --git a/tests/helpers.py b/tests/helpers.py
index 3c208ab6cc5..31233b827b9 100644
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import shutil
import urllib.parse
@@ -5,10 +7,6 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Union
from poetry.core.masonry.utils.helpers import escape_name
from poetry.core.masonry.utils.helpers import escape_version
@@ -38,17 +36,17 @@
FIXTURE_PATH = Path(__file__).parent / "fixtures"
-def get_package(name: str, version: Union[str, "Version"]) -> Package:
+def get_package(name: str, version: str | Version) -> Package:
return Package(name, version)
def get_dependency(
name: str,
- constraint: Optional[Union[str, Dict[str, Any]]] = None,
- groups: Optional[List[str]] = None,
+ constraint: str | dict[str, Any] | None = None,
+ groups: list[str] | None = None,
optional: bool = False,
allows_prereleases: bool = False,
-) -> "DependencyTypes":
+) -> DependencyTypes:
if constraint is None:
constraint = "*"
@@ -61,7 +59,7 @@ def get_dependency(
return Factory.create_dependency(name, constraint or "*", groups=groups)
-def fixture(path: Optional[str] = None) -> Path:
+def fixture(path: str | None = None) -> Path:
if path:
return FIXTURE_PATH / path
else:
@@ -125,35 +123,35 @@ def __init__(self, *args: Any, **kwargs: Any):
self._uninstalls = []
@property
- def installations(self) -> List[Package]:
+ def installations(self) -> list[Package]:
return self._installs
@property
- def updates(self) -> List[Package]:
+ def updates(self) -> list[Package]:
return self._updates
@property
- def removals(self) -> List[Package]:
+ def removals(self) -> list[Package]:
return self._uninstalls
- def _do_execute_operation(self, operation: "OperationTypes") -> None:
+ def _do_execute_operation(self, operation: OperationTypes) -> None:
super()._do_execute_operation(operation)
if not operation.skipped:
getattr(self, f"_{operation.job_type}s").append(operation.package)
- def _execute_install(self, operation: "OperationTypes") -> int:
+ def _execute_install(self, operation: OperationTypes) -> int:
return 0
- def _execute_update(self, operation: "OperationTypes") -> int:
+ def _execute_update(self, operation: OperationTypes) -> int:
return 0
- def _execute_remove(self, operation: "OperationTypes") -> int:
+ def _execute_remove(self, operation: OperationTypes) -> int:
return 0
class PoetryTestApplication(Application):
- def __init__(self, poetry: "Poetry"):
+ def __init__(self, poetry: Poetry):
super().__init__()
self._poetry = poetry
@@ -168,7 +166,7 @@ def reset_poetry(self) -> None:
class TestLocker(Locker):
- def __init__(self, lock: Union[str, Path], local_config: Dict):
+ def __init__(self, lock: str | Path, local_config: dict):
self._lock = TOMLFile(lock)
self._local_config = local_config
self._lock_data = None
@@ -183,12 +181,12 @@ def write(self, write: bool = True) -> None:
def is_locked(self) -> bool:
return self._locked
- def locked(self, is_locked: bool = True) -> "TestLocker":
+ def locked(self, is_locked: bool = True) -> TestLocker:
self._locked = is_locked
return self
- def mock_lock_data(self, data: Dict) -> None:
+ def mock_lock_data(self, data: dict) -> None:
self.locked()
self._lock_data = data
@@ -196,7 +194,7 @@ def mock_lock_data(self, data: Dict) -> None:
def is_fresh(self) -> bool:
return True
- def _write_lock_data(self, data: "TOMLDocument") -> None:
+ def _write_lock_data(self, data: TOMLDocument) -> None:
if self._write:
super()._write_lock_data(data)
self._locked = True
@@ -206,14 +204,14 @@ def _write_lock_data(self, data: "TOMLDocument") -> None:
class TestRepository(Repository):
- def find_packages(self, dependency: "Dependency") -> List[Package]:
+ def find_packages(self, dependency: Dependency) -> list[Package]:
packages = super().find_packages(dependency)
if len(packages) == 0:
raise PackageNotFound(f"Package [{dependency.name}] not found.")
return packages
- def find_links_for_package(self, package: Package) -> List[Link]:
+ def find_links_for_package(self, package: Package) -> list[Link]:
return [
Link(
f"https://foo.bar/files/{escape_name(package.name)}"
diff --git a/tests/inspection/test_info.py b/tests/inspection/test_info.py
index 075fd931e87..c242fb90937 100644
--- a/tests/inspection/test_info.py
+++ b/tests/inspection/test_info.py
@@ -1,7 +1,8 @@
+from __future__ import annotations
+
from pathlib import Path
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
-from typing import Set
import pytest
@@ -95,7 +96,7 @@ def demo_setup_complex_pep517_legacy(demo_setup_complex: Path) -> Path:
return demo_setup_complex
-def demo_check_info(info: PackageInfo, requires_dist: Set[str] = None) -> None:
+def demo_check_info(info: PackageInfo, requires_dist: set[str] = None) -> None:
assert info.name == "demo"
assert info.version == "0.1.0"
assert info.requires_dist
@@ -157,14 +158,14 @@ def test_info_no_setup_pkg_info_no_deps():
assert info.requires_dist is None
-def test_info_setup_simple(mocker: "MockerFixture", demo_setup: Path):
+def test_info_setup_simple(mocker: MockerFixture, demo_setup: Path):
spy = mocker.spy(VirtualEnv, "run")
info = PackageInfo.from_directory(demo_setup)
assert spy.call_count == 0
demo_check_info(info, requires_dist={"package"})
-def test_info_setup_cfg(mocker: "MockerFixture", demo_setup_cfg: Path):
+def test_info_setup_cfg(mocker: MockerFixture, demo_setup_cfg: Path):
spy = mocker.spy(VirtualEnv, "run")
info = PackageInfo.from_directory(demo_setup_cfg)
assert spy.call_count == 0
@@ -177,7 +178,7 @@ def test_info_setup_complex(demo_setup_complex: Path):
def test_info_setup_complex_pep517_error(
- mocker: "MockerFixture", demo_setup_complex: Path
+ mocker: MockerFixture, demo_setup_complex: Path
):
mocker.patch(
"poetry.utils.env.VirtualEnv.run",
@@ -195,7 +196,7 @@ def test_info_setup_complex_pep517_legacy(demo_setup_complex_pep517_legacy: Path
def test_info_setup_complex_disable_build(
- mocker: "MockerFixture", demo_setup_complex: Path
+ mocker: MockerFixture, demo_setup_complex: Path
):
spy = mocker.spy(VirtualEnv, "run")
info = PackageInfo.from_directory(demo_setup_complex, disable_build=True)
@@ -207,7 +208,7 @@ def test_info_setup_complex_disable_build(
@pytest.mark.parametrize("missing", ["version", "name", "install_requires"])
def test_info_setup_missing_mandatory_should_trigger_pep517(
- mocker: "MockerFixture", source_dir: Path, missing: str
+ mocker: MockerFixture, source_dir: Path, missing: str
):
setup = "from setuptools import setup; "
setup += "setup("
diff --git a/tests/installation/test_chef.py b/tests/installation/test_chef.py
index 25d56aadd54..ccd6666f7ee 100644
--- a/tests/installation/test_chef.py
+++ b/tests/installation/test_chef.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
@@ -14,7 +16,7 @@
from tests.conftest import Config
-def test_get_cached_archive_for_link(config: "Config", mocker: "MockerFixture"):
+def test_get_cached_archive_for_link(config: Config, mocker: MockerFixture):
chef = Chef(
config,
MockEnv(
@@ -45,7 +47,7 @@ def test_get_cached_archive_for_link(config: "Config", mocker: "MockerFixture"):
assert Link("file:///foo/demo-0.1.0-cp38-cp38-macosx_10_15_x86_64.whl") == archive
-def test_get_cached_archives_for_link(config: "Config", mocker: "MockerFixture"):
+def test_get_cached_archives_for_link(config: Config, mocker: MockerFixture):
chef = Chef(
config,
MockEnv(
@@ -70,7 +72,7 @@ def test_get_cached_archives_for_link(config: "Config", mocker: "MockerFixture")
}
-def test_get_cache_directory_for_link(config: "Config", config_cache_dir: Path):
+def test_get_cache_directory_for_link(config: Config, config_cache_dir: Path):
chef = Chef(
config,
MockEnv(
diff --git a/tests/installation/test_chooser.py b/tests/installation/test_chooser.py
index 0fb40affe0c..973e4842ff6 100644
--- a/tests/installation/test_chooser.py
+++ b/tests/installation/test_chooser.py
@@ -1,13 +1,10 @@
+from __future__ import annotations
+
import re
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Type
-from typing import Union
import pytest
@@ -45,10 +42,10 @@ def env() -> MockEnv:
@pytest.fixture()
-def mock_pypi(http: Type["httpretty.httpretty"]) -> None:
+def mock_pypi(http: type[httpretty.httpretty]) -> None:
def callback(
- request: "HTTPrettyRequest", uri: str, headers: Dict[str, Any]
- ) -> Optional[List[Union[int, Dict[str, Any], str]]]:
+ request: HTTPrettyRequest, uri: str, headers: dict[str, Any]
+ ) -> list[int | dict[str, Any] | str] | None:
parts = uri.rsplit("/")
name = parts[-3]
@@ -72,10 +69,10 @@ def callback(
@pytest.fixture()
-def mock_legacy(http: Type["httpretty.httpretty"]) -> None:
+def mock_legacy(http: type[httpretty.httpretty]) -> None:
def callback(
- request: "HTTPrettyRequest", uri: str, headers: Dict[str, Any]
- ) -> List[Union[int, Dict[str, Any], str]]:
+ request: HTTPrettyRequest, uri: str, headers: dict[str, Any]
+ ) -> list[int | dict[str, Any] | str]:
parts = uri.rsplit("/")
name = parts[-2]
diff --git a/tests/installation/test_executor.py b/tests/installation/test_executor.py
index 1f4b46f8588..7c453643400 100644
--- a/tests/installation/test_executor.py
+++ b/tests/installation/test_executor.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import json
import re
import shutil
@@ -5,11 +7,6 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Type
-from typing import Union
import pytest
@@ -82,10 +79,10 @@ def pool() -> Pool:
@pytest.fixture()
-def mock_file_downloads(http: Type["httpretty.httpretty"]) -> None:
+def mock_file_downloads(http: type[httpretty.httpretty]) -> None:
def callback(
- request: "HTTPrettyRequest", uri: str, headers: Dict[str, Any]
- ) -> List[Union[int, Dict[str, Any], str]]:
+ request: HTTPrettyRequest, uri: str, headers: dict[str, Any]
+ ) -> list[int | dict[str, Any] | str]:
fixture = Path(__file__).parent.parent.joinpath(
"fixtures/distributions/demo-0.1.0-py2.py3-none-any.whl"
)
@@ -101,8 +98,8 @@ def callback(
def test_execute_executes_a_batch_of_operations(
- mocker: "MockerFixture",
- config: "Config",
+ mocker: MockerFixture,
+ config: Config,
pool: Pool,
io: BufferedIO,
tmp_dir: str,
@@ -180,7 +177,7 @@ def test_execute_executes_a_batch_of_operations(
def test_execute_shows_skipped_operations_if_verbose(
- config: "Config", pool: Pool, io: BufferedIO, config_cache_dir: Path, env: MockEnv
+ config: Config, pool: Pool, io: BufferedIO, config_cache_dir: Path, env: MockEnv
):
config.merge({"cache-dir": config_cache_dir.as_posix()})
@@ -204,7 +201,7 @@ def test_execute_shows_skipped_operations_if_verbose(
def test_execute_should_show_errors(
- config: "Config", pool: Pool, mocker: "MockerFixture", io: BufferedIO, env: MockEnv
+ config: Config, pool: Pool, mocker: MockerFixture, io: BufferedIO, env: MockEnv
):
executor = Executor(env, pool, config, io)
executor.verbose()
@@ -227,8 +224,8 @@ def test_execute_should_show_errors(
def test_execute_works_with_ansi_output(
- mocker: "MockerFixture",
- config: "Config",
+ mocker: MockerFixture,
+ config: Config,
pool: Pool,
io_decorated: BufferedIO,
tmp_dir: str,
@@ -269,8 +266,8 @@ def test_execute_works_with_ansi_output(
def test_execute_works_with_no_ansi_output(
- mocker: "MockerFixture",
- config: "Config",
+ mocker: MockerFixture,
+ config: Config,
pool: Pool,
io_not_decorated: BufferedIO,
tmp_dir: str,
@@ -304,7 +301,7 @@ def test_execute_works_with_no_ansi_output(
def test_execute_should_show_operation_as_cancelled_on_subprocess_keyboard_interrupt(
- config: "Config", pool: Pool, mocker: "MockerFixture", io: BufferedIO, env: MockEnv
+ config: Config, pool: Pool, mocker: MockerFixture, io: BufferedIO, env: MockEnv
):
executor = Executor(env, pool, config, io)
executor.verbose()
@@ -325,7 +322,7 @@ def test_execute_should_show_operation_as_cancelled_on_subprocess_keyboard_inter
def test_execute_should_gracefully_handle_io_error(
- config: "Config", pool: Pool, mocker: "MockerFixture", io: BufferedIO, env: MockEnv
+ config: Config, pool: Pool, mocker: MockerFixture, io: BufferedIO, env: MockEnv
):
executor = Executor(env, pool, config, io)
executor.verbose()
@@ -352,10 +349,10 @@ def write_line(string: str, **kwargs: Any) -> None:
def test_executor_should_delete_incomplete_downloads(
- config: "Config",
+ config: Config,
io: BufferedIO,
tmp_dir: str,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
pool: Pool,
mock_file_downloads: None,
env: MockEnv,
@@ -389,7 +386,7 @@ def test_executor_should_delete_incomplete_downloads(
def verify_installed_distribution(
- venv: "VirtualEnv", package: Package, url_reference: Optional[Dict[str, Any]] = None
+ venv: VirtualEnv, package: Package, url_reference: dict[str, Any] | None = None
):
distributions = list(venv.site_packages.distributions(name=package.name))
assert len(distributions) == 1
@@ -415,7 +412,7 @@ def verify_installed_distribution(
def test_executor_should_write_pep610_url_references_for_files(
- tmp_venv: "VirtualEnv", pool: Pool, config: "Config", io: BufferedIO
+ tmp_venv: VirtualEnv, pool: Pool, config: Config, io: BufferedIO
):
url = (
Path(__file__)
@@ -434,7 +431,7 @@ def test_executor_should_write_pep610_url_references_for_files(
def test_executor_should_write_pep610_url_references_for_directories(
- tmp_venv: "VirtualEnv", pool: Pool, config: "Config", io: BufferedIO
+ tmp_venv: VirtualEnv, pool: Pool, config: Config, io: BufferedIO
):
url = Path(__file__).parent.parent.joinpath("fixtures/simple_project").resolve()
package = Package(
@@ -449,7 +446,7 @@ def test_executor_should_write_pep610_url_references_for_directories(
def test_executor_should_write_pep610_url_references_for_editable_directories(
- tmp_venv: "VirtualEnv", pool: Pool, config: "Config", io: BufferedIO
+ tmp_venv: VirtualEnv, pool: Pool, config: Config, io: BufferedIO
):
url = Path(__file__).parent.parent.joinpath("fixtures/simple_project").resolve()
package = Package(
@@ -468,9 +465,9 @@ def test_executor_should_write_pep610_url_references_for_editable_directories(
def test_executor_should_write_pep610_url_references_for_urls(
- tmp_venv: "VirtualEnv",
+ tmp_venv: VirtualEnv,
pool: Pool,
- config: "Config",
+ config: Config,
io: BufferedIO,
mock_file_downloads: None,
):
@@ -489,9 +486,9 @@ def test_executor_should_write_pep610_url_references_for_urls(
def test_executor_should_write_pep610_url_references_for_git(
- tmp_venv: "VirtualEnv",
+ tmp_venv: VirtualEnv,
pool: Pool,
- config: "Config",
+ config: Config,
io: BufferedIO,
mock_file_downloads: None,
):
@@ -521,12 +518,12 @@ def test_executor_should_write_pep610_url_references_for_git(
def test_executor_should_use_cached_link_and_hash(
- tmp_venv: "VirtualEnv",
+ tmp_venv: VirtualEnv,
pool: Pool,
- config: "Config",
+ config: Config,
io: BufferedIO,
- mocker: "MockerFixture",
- fixture_dir: "FixtureDirGetter",
+ mocker: MockerFixture,
+ fixture_dir: FixtureDirGetter,
):
# Produce a file:/// URI that is a valid link
link_cached = Link(
@@ -568,14 +565,14 @@ def test_executor_should_use_cached_link_and_hash(
],
)
def test_executor_should_be_initialized_with_correct_workers(
- tmp_venv: "VirtualEnv",
+ tmp_venv: VirtualEnv,
pool: Pool,
- config: "Config",
+ config: Config,
io: BufferedIO,
- mocker: "MockerFixture",
- max_workers: Optional[int],
- cpu_count: Optional[int],
- side_effect: Optional[Exception],
+ mocker: MockerFixture,
+ max_workers: int | None,
+ cpu_count: int | None,
+ side_effect: Exception | None,
expected_workers: int,
):
config.merge({"installer": {"max-workers": max_workers}})
diff --git a/tests/installation/test_installer.py b/tests/installation/test_installer.py
index fef1ee5c426..812ea12b196 100644
--- a/tests/installation/test_installer.py
+++ b/tests/installation/test_installer.py
@@ -1,14 +1,11 @@
+from __future__ import annotations
+
import itertools
import json
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Tuple
-from typing import Union
import pytest
@@ -62,68 +59,68 @@ class Executor(BaseExecutor):
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
- self._installs: List["DependencyPackage"] = []
- self._updates: List["DependencyPackage"] = []
- self._uninstalls: List["DependencyPackage"] = []
+ self._installs: list[DependencyPackage] = []
+ self._updates: list[DependencyPackage] = []
+ self._uninstalls: list[DependencyPackage] = []
@property
- def installations(self) -> List["DependencyPackage"]:
+ def installations(self) -> list[DependencyPackage]:
return self._installs
@property
- def updates(self) -> List["DependencyPackage"]:
+ def updates(self) -> list[DependencyPackage]:
return self._updates
@property
- def removals(self) -> List["DependencyPackage"]:
+ def removals(self) -> list[DependencyPackage]:
return self._uninstalls
- def _do_execute_operation(self, operation: "OperationTypes") -> None:
+ def _do_execute_operation(self, operation: OperationTypes) -> None:
super()._do_execute_operation(operation)
if not operation.skipped:
getattr(self, f"_{operation.job_type}s").append(operation.package)
- def _execute_install(self, operation: "OperationTypes") -> int:
+ def _execute_install(self, operation: OperationTypes) -> int:
return 0
- def _execute_update(self, operation: "OperationTypes") -> int:
+ def _execute_update(self, operation: OperationTypes) -> int:
return 0
- def _execute_uninstall(self, operation: "OperationTypes") -> int:
+ def _execute_uninstall(self, operation: OperationTypes) -> int:
return 0
class CustomInstalledRepository(InstalledRepository):
@classmethod
def load(
- cls, env: "Env", with_dependencies: bool = False
- ) -> "CustomInstalledRepository":
+ cls, env: Env, with_dependencies: bool = False
+ ) -> CustomInstalledRepository:
return cls()
class Locker(BaseLocker):
- def __init__(self, lock_path: Union[str, Path]):
+ def __init__(self, lock_path: str | Path):
self._lock = TOMLFile(Path(lock_path).joinpath("poetry.lock"))
self._written_data = None
self._locked = False
self._content_hash = self._get_content_hash()
@property
- def written_data(self) -> Optional[Dict]:
+ def written_data(self) -> dict | None:
return self._written_data
- def set_lock_path(self, lock: Union[str, Path]) -> "Locker":
+ def set_lock_path(self, lock: str | Path) -> Locker:
self._lock = TOMLFile(Path(lock).joinpath("poetry.lock"))
return self
- def locked(self, is_locked: bool = True) -> "Locker":
+ def locked(self, is_locked: bool = True) -> Locker:
self._locked = is_locked
return self
- def mock_lock_data(self, data: Dict) -> None:
+ def mock_lock_data(self, data: dict) -> None:
self._lock_data = data
def is_locked(self) -> bool:
@@ -135,7 +132,7 @@ def is_fresh(self) -> bool:
def _get_content_hash(self) -> str:
return "123456789"
- def _write_lock_data(self, data: Dict) -> None:
+ def _write_lock_data(self, data: dict) -> None:
for package in data["package"]:
python_versions = str(package["python-versions"])
package["python-versions"] = python_versions
@@ -187,7 +184,7 @@ def installer(
locker: Locker,
env: NullEnv,
installed: CustomInstalledRepository,
- config: "Config",
+ config: Config,
) -> Installer:
installer = Installer(
NullIO(),
@@ -204,7 +201,7 @@ def installer(
return installer
-def fixture(name: str) -> Dict:
+def fixture(name: str) -> dict:
file = TOMLFile(Path(__file__).parent / "fixtures" / f"{name}.test")
return json.loads(json.dumps(file.read()))
@@ -668,7 +665,7 @@ def test_run_install_with_optional_group_selected(
),
)
def test_run_install_with_synchronization(
- managed_reserved_package_names: Tuple[str, ...],
+ managed_reserved_package_names: tuple[str, ...],
installer: Installer,
locker: Locker,
repo: Repository,
@@ -944,7 +941,7 @@ def test_run_with_optional_and_platform_restricted_dependencies(
locker: Locker,
repo: Repository,
package: ProjectPackage,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
):
mocker.patch("sys.platform", "darwin")
@@ -1174,7 +1171,7 @@ def test_installer_with_pypi_repository(
package: ProjectPackage,
locker: Locker,
installed: CustomInstalledRepository,
- config: "Config",
+ config: Config,
):
pool = Pool()
pool.add_repository(MockRepository())
@@ -1195,7 +1192,7 @@ def test_run_installs_with_local_file(
locker: Locker,
repo: Repository,
package: ProjectPackage,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir("distributions/demo-0.1.0-py2.py3-none-any.whl")
package.add_dependency(Factory.create_dependency("demo", {"file": str(file_path)}))
@@ -1215,7 +1212,7 @@ def test_run_installs_wheel_with_no_requires_dist(
locker: Locker,
repo: Repository,
package: ProjectPackage,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir(
"wheel_with_no_requires_dist/demo-0.1.0-py2.py3-none-any.whl"
@@ -1237,7 +1234,7 @@ def test_run_installs_with_local_poetry_directory_and_extras(
repo: Repository,
package: ProjectPackage,
tmpdir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir("project_with_extras")
package.add_dependency(
@@ -1262,7 +1259,7 @@ def test_run_installs_with_local_poetry_directory_transitive(
repo: Repository,
package: ProjectPackage,
tmpdir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
root_dir = fixture_dir("directory")
package.root_dir = root_dir
@@ -1294,7 +1291,7 @@ def test_run_installs_with_local_poetry_file_transitive(
repo: Repository,
package: ProjectPackage,
tmpdir: str,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
root_dir = fixture_dir("directory")
package.root_dir = root_dir
@@ -1328,7 +1325,7 @@ def test_run_installs_with_local_setuptools_directory(
repo: Repository,
package: ProjectPackage,
tmpdir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir("project_with_setup/")
package.add_dependency(
@@ -1909,7 +1906,7 @@ def test_installer_required_extras_should_not_be_removed_when_updating_single_de
installed: CustomInstalledRepository,
env: NullEnv,
pool: Pool,
- config: "Config",
+ config: Config,
):
package.add_dependency(Factory.create_dependency("A", {"version": "^1.0"}))
@@ -1974,8 +1971,8 @@ def test_installer_required_extras_should_not_be_removed_when_updating_single_de
package: ProjectPackage,
installed: CustomInstalledRepository,
env: NullEnv,
- mocker: "MockerFixture",
- config: "Config",
+ mocker: MockerFixture,
+ config: Config,
):
mocker.patch("sys.platform", "darwin")
@@ -2038,7 +2035,7 @@ def test_installer_required_extras_should_be_installed(
package: ProjectPackage,
installed: CustomInstalledRepository,
env: NullEnv,
- config: "Config",
+ config: Config,
):
pool = Pool()
pool.add_repository(MockRepository())
@@ -2175,7 +2172,7 @@ def test_installer_can_install_dependencies_from_forced_source(
package: Package,
installed: CustomInstalledRepository,
env: NullEnv,
- config: "Config",
+ config: Config,
):
package.python_versions = "^3.7"
package.add_dependency(
@@ -2258,7 +2255,7 @@ def test_installer_can_handle_old_lock_files(
package: ProjectPackage,
repo: Repository,
installed: CustomInstalledRepository,
- config: "Config",
+ config: Config,
):
pool = Pool()
pool.add_repository(MockRepository())
diff --git a/tests/installation/test_installer_old.py b/tests/installation/test_installer_old.py
index d1478fcccd6..54ed3322755 100644
--- a/tests/installation/test_installer_old.py
+++ b/tests/installation/test_installer_old.py
@@ -1,11 +1,9 @@
+from __future__ import annotations
+
import itertools
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import Optional
-from typing import Tuple
-from typing import Union
import pytest
@@ -50,33 +48,33 @@ def _get_installer(self) -> NoopInstaller:
class CustomInstalledRepository(InstalledRepository):
@classmethod
def load(
- cls, env: "Env", with_dependencies: bool = False
- ) -> "CustomInstalledRepository":
+ cls, env: Env, with_dependencies: bool = False
+ ) -> CustomInstalledRepository:
return cls()
class Locker(BaseLocker):
- def __init__(self, lock_path: Union[str, Path]):
+ def __init__(self, lock_path: str | Path):
self._lock = TOMLFile(Path(lock_path).joinpath("poetry.lock"))
self._written_data = None
self._locked = False
self._content_hash = self._get_content_hash()
@property
- def written_data(self) -> Optional[Dict]:
+ def written_data(self) -> dict | None:
return self._written_data
- def set_lock_path(self, lock: Union[str, Path]) -> "Locker":
+ def set_lock_path(self, lock: str | Path) -> Locker:
self._lock = TOMLFile(Path(lock).joinpath("poetry.lock"))
return self
- def locked(self, is_locked: bool = True) -> "Locker":
+ def locked(self, is_locked: bool = True) -> Locker:
self._locked = is_locked
return self
- def mock_lock_data(self, data: Dict) -> None:
+ def mock_lock_data(self, data: dict) -> None:
self._lock_data = data
def is_locked(self) -> bool:
@@ -88,7 +86,7 @@ def is_fresh(self) -> bool:
def _get_content_hash(self) -> str:
return "123456789"
- def _write_lock_data(self, data: Dict) -> None:
+ def _write_lock_data(self, data: dict) -> None:
for package in data["package"]:
python_versions = str(package["python-versions"])
package["python-versions"] = python_versions
@@ -140,7 +138,7 @@ def installer(
locker: Locker,
env: NullEnv,
installed: CustomInstalledRepository,
- config: "Config",
+ config: Config,
):
return Installer(NullIO(), env, package, locker, pool, config, installed=installed)
@@ -337,7 +335,7 @@ def test_run_install_no_group(
),
)
def test_run_install_with_synchronization(
- managed_reserved_package_names: Tuple[str, ...],
+ managed_reserved_package_names: tuple[str, ...],
installer: Installer,
locker: Locker,
repo: Repository,
@@ -617,7 +615,7 @@ def test_run_with_optional_and_platform_restricted_dependencies(
locker: Locker,
repo: Repository,
package: ProjectPackage,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
):
mocker.patch("sys.platform", "darwin")
@@ -821,7 +819,7 @@ def test_installer_with_pypi_repository(
package: ProjectPackage,
locker: Locker,
installed: CustomInstalledRepository,
- config: "Config",
+ config: Config,
):
pool = Pool()
pool.add_repository(MockRepository())
@@ -842,7 +840,7 @@ def test_run_installs_with_local_file(
locker: Locker,
repo: Repository,
package: ProjectPackage,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir("distributions/demo-0.1.0-py2.py3-none-any.whl")
package.add_dependency(Factory.create_dependency("demo", {"file": str(file_path)}))
@@ -863,7 +861,7 @@ def test_run_installs_wheel_with_no_requires_dist(
locker: Locker,
repo: Repository,
package: ProjectPackage,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir(
"wheel_with_no_requires_dist/demo-0.1.0-py2.py3-none-any.whl"
@@ -885,7 +883,7 @@ def test_run_installs_with_local_poetry_directory_and_extras(
repo: Repository,
package: ProjectPackage,
tmpdir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir("project_with_extras")
package.add_dependency(
@@ -911,7 +909,7 @@ def test_run_installs_with_local_poetry_directory_transitive(
repo: Repository,
package: ProjectPackage,
tmpdir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
root_dir = fixture_dir("directory")
package.root_dir = root_dir
@@ -943,7 +941,7 @@ def test_run_installs_with_local_poetry_file_transitive(
repo: Repository,
package: ProjectPackage,
tmpdir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
root_dir = fixture_dir("directory")
package.root_dir = root_dir
@@ -975,7 +973,7 @@ def test_run_installs_with_local_setuptools_directory(
repo: Repository,
package: ProjectPackage,
tmpdir: Path,
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
):
file_path = fixture_dir("project_with_setup/")
package.add_dependency(
@@ -1570,7 +1568,7 @@ def test_installer_required_extras_should_not_be_removed_when_updating_single_de
installed: CustomInstalledRepository,
env: NullEnv,
pool: Pool,
- config: "Config",
+ config: Config,
):
package.add_dependency(Factory.create_dependency("A", {"version": "^1.0"}))
@@ -1627,8 +1625,8 @@ def test_installer_required_extras_should_not_be_removed_when_updating_single_de
package: ProjectPackage,
installed: CustomInstalledRepository,
env: NullEnv,
- mocker: "MockerFixture",
- config: "Config",
+ mocker: MockerFixture,
+ config: Config,
):
mocker.patch("sys.platform", "darwin")
@@ -1675,7 +1673,7 @@ def test_installer_required_extras_should_be_installed(
package: ProjectPackage,
installed: CustomInstalledRepository,
env: NullEnv,
- config: "Config",
+ config: Config,
):
pool = Pool()
pool.add_repository(MockRepository())
@@ -1796,7 +1794,7 @@ def test_installer_can_install_dependencies_from_forced_source(
package: ProjectPackage,
installed: CustomInstalledRepository,
env: NullEnv,
- config: "Config",
+ config: Config,
):
package.python_versions = "^3.7"
package.add_dependency(
@@ -1871,7 +1869,7 @@ def test_installer_can_handle_old_lock_files(
package: ProjectPackage,
repo: Repository,
installed: CustomInstalledRepository,
- config: "Config",
+ config: Config,
):
pool = Pool()
pool.add_repository(MockRepository())
diff --git a/tests/installation/test_pip_installer.py b/tests/installation/test_pip_installer.py
index 91956c0368d..719df21cd5b 100644
--- a/tests/installation/test_pip_installer.py
+++ b/tests/installation/test_pip_installer.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import re
import shutil
@@ -186,7 +188,7 @@ def test_requirement_git_develop_true(installer: PipInstaller, package_git: Pack
def test_uninstall_git_package_nspkg_pth_cleanup(
- mocker: "MockerFixture", tmp_venv: "VirtualEnv", pool: Pool
+ mocker: MockerFixture, tmp_venv: VirtualEnv, pool: Pool
):
# this test scenario requires a real installation using the pip installer
installer = PipInstaller(tmp_venv, NullIO(), pool)
diff --git a/tests/masonry/builders/fixtures/excluded_subpackage/example/__init__.py b/tests/masonry/builders/fixtures/excluded_subpackage/example/__init__.py
index 3dc1f76bc69..4e562f46413 100644
--- a/tests/masonry/builders/fixtures/excluded_subpackage/example/__init__.py
+++ b/tests/masonry/builders/fixtures/excluded_subpackage/example/__init__.py
@@ -1 +1,4 @@
+from __future__ import annotations
+
+
__version__ = "0.1.0"
diff --git a/tests/masonry/builders/fixtures/excluded_subpackage/example/test/excluded.py b/tests/masonry/builders/fixtures/excluded_subpackage/example/test/excluded.py
index 320477c09c3..3bf5a9331b5 100644
--- a/tests/masonry/builders/fixtures/excluded_subpackage/example/test/excluded.py
+++ b/tests/masonry/builders/fixtures/excluded_subpackage/example/test/excluded.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from tests.masonry.builders.fixtures.excluded_subpackage.example import __version__
diff --git a/tests/masonry/builders/test_editable_builder.py b/tests/masonry/builders/test_editable_builder.py
index 67ce0d2cea5..7091b1f87e5 100644
--- a/tests/masonry/builders/test_editable_builder.py
+++ b/tests/masonry/builders/test_editable_builder.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import shutil
@@ -22,7 +24,7 @@
@pytest.fixture()
-def simple_poetry() -> "Poetry":
+def simple_poetry() -> Poetry:
poetry = Factory().create_poetry(
Path(__file__).parent.parent.parent / "fixtures" / "simple_project"
)
@@ -31,7 +33,7 @@ def simple_poetry() -> "Poetry":
@pytest.fixture()
-def project_with_include() -> "Poetry":
+def project_with_include() -> Poetry:
poetry = Factory().create_poetry(
Path(__file__).parent.parent.parent / "fixtures" / "with-include"
)
@@ -40,7 +42,7 @@ def project_with_include() -> "Poetry":
@pytest.fixture()
-def extended_poetry() -> "Poetry":
+def extended_poetry() -> Poetry:
poetry = Factory().create_poetry(
Path(__file__).parent.parent.parent / "fixtures" / "extended_project"
)
@@ -49,7 +51,7 @@ def extended_poetry() -> "Poetry":
@pytest.fixture()
-def extended_without_setup_poetry() -> "Poetry":
+def extended_without_setup_poetry() -> Poetry:
poetry = Factory().create_poetry(
Path(__file__).parent.parent.parent
/ "fixtures"
@@ -60,7 +62,7 @@ def extended_without_setup_poetry() -> "Poetry":
@pytest.fixture()
-def env_manager(simple_poetry: "Poetry") -> EnvManager:
+def env_manager(simple_poetry: Poetry) -> EnvManager:
return EnvManager(simple_poetry)
@@ -77,7 +79,7 @@ def tmp_venv(tmp_dir: str, env_manager: EnvManager) -> VirtualEnv:
def test_builder_installs_proper_files_for_standard_packages(
- simple_poetry: "Poetry", tmp_venv: VirtualEnv
+ simple_poetry: Poetry, tmp_venv: VirtualEnv
):
builder = EditableBuilder(simple_poetry, tmp_venv, NullIO())
@@ -188,7 +190,7 @@ def test_builder_installs_proper_files_for_standard_packages(
def test_builder_falls_back_on_setup_and_pip_for_packages_with_build_scripts(
- mocker: "MockerFixture", extended_poetry: "Poetry", tmp_dir: str
+ mocker: MockerFixture, extended_poetry: Poetry, tmp_dir: str
):
pip_editable_install = mocker.patch(
"poetry.masonry.builders.editable.pip_editable_install"
@@ -204,7 +206,7 @@ def test_builder_falls_back_on_setup_and_pip_for_packages_with_build_scripts(
def test_builder_installs_proper_files_when_packages_configured(
- project_with_include: "Poetry", tmp_venv: VirtualEnv
+ project_with_include: Poetry, tmp_venv: VirtualEnv
):
builder = EditableBuilder(project_with_include, tmp_venv, NullIO())
builder.build()
@@ -229,7 +231,7 @@ def test_builder_installs_proper_files_when_packages_configured(
def test_builder_should_execute_build_scripts(
- extended_without_setup_poetry: "Poetry", tmp_dir: str
+ extended_without_setup_poetry: Poetry, tmp_dir: str
):
env = MockEnv(path=Path(tmp_dir) / "foo")
builder = EditableBuilder(extended_without_setup_poetry, env, NullIO())
diff --git a/tests/mixology/helpers.py b/tests/mixology/helpers.py
index b595fbcd4d7..cf3f5f81621 100644
--- a/tests/mixology/helpers.py
+++ b/tests/mixology/helpers.py
@@ -1,7 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
-from typing import Optional
from poetry.core.packages.package import Package
@@ -18,11 +17,11 @@
def add_to_repo(
- repository: "Repository",
+ repository: Repository,
name: str,
version: str,
- deps: Optional[Dict[str, str]] = None,
- python: Optional[str] = None,
+ deps: dict[str, str] | None = None,
+ python: str | None = None,
) -> None:
package = Package(name, version)
if python:
@@ -36,13 +35,13 @@ def add_to_repo(
def check_solver_result(
- root: "ProjectPackage",
- provider: "Provider",
- result: Optional[Dict[str, str]] = None,
- error: Optional[str] = None,
- tries: Optional[int] = None,
- locked: Optional[Dict[str, Package]] = None,
- use_latest: Optional[List[str]] = None,
+ root: ProjectPackage,
+ provider: Provider,
+ result: dict[str, str] | None = None,
+ error: str | None = None,
+ tries: int | None = None,
+ locked: dict[str, Package] | None = None,
+ use_latest: list[str] | None = None,
) -> None:
if locked is not None:
locked = {k: DependencyPackage(l.to_dependency(), l) for k, l in locked.items()}
diff --git a/tests/mixology/solutions/providers/test_python_requirement_solution_provider.py b/tests/mixology/solutions/providers/test_python_requirement_solution_provider.py
index c52e4ccd88d..c34e93224f7 100644
--- a/tests/mixology/solutions/providers/test_python_requirement_solution_provider.py
+++ b/tests/mixology/solutions/providers/test_python_requirement_solution_provider.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from poetry.core.packages.dependency import Dependency
from poetry.mixology.failure import SolveFailure
diff --git a/tests/mixology/solutions/solutions/test_python_requirement_solution.py b/tests/mixology/solutions/solutions/test_python_requirement_solution.py
index 3cccef48b32..9c8950ae396 100644
--- a/tests/mixology/solutions/solutions/test_python_requirement_solution.py
+++ b/tests/mixology/solutions/solutions/test_python_requirement_solution.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from cleo.io.buffered_io import BufferedIO
from poetry.core.packages.dependency import Dependency
diff --git a/tests/mixology/version_solver/__init__.py b/tests/mixology/version_solver/__init__.py
index 2382bd6f2a0..b7473c5bf9d 100644
--- a/tests/mixology/version_solver/__init__.py
+++ b/tests/mixology/version_solver/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import pytest
diff --git a/tests/mixology/version_solver/conftest.py b/tests/mixology/version_solver/conftest.py
index 0fa40676a4a..fd347cd9471 100644
--- a/tests/mixology/version_solver/conftest.py
+++ b/tests/mixology/version_solver/conftest.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
import pytest
@@ -26,7 +28,7 @@ def repo() -> Repository:
@pytest.fixture
-def pool(repo: "TestRepository") -> Pool:
+def pool(repo: TestRepository) -> Pool:
pool = Pool()
pool.add_repository(repo)
diff --git a/tests/mixology/version_solver/test_backtracking.py b/tests/mixology/version_solver/test_backtracking.py
index 285ea9eb27a..bdbbfba11cc 100644
--- a/tests/mixology/version_solver/test_backtracking.py
+++ b/tests/mixology/version_solver/test_backtracking.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.factory import Factory
@@ -12,7 +14,7 @@
def test_circular_dependency_on_older_version(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("a", ">=1.0.0"))
@@ -24,7 +26,7 @@ def test_circular_dependency_on_older_version(
def test_diamond_dependency_graph(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("a", "*"))
root.add_dependency(Factory.create_dependency("b", "*"))
@@ -43,7 +45,7 @@ def test_diamond_dependency_graph(
def test_backjumps_after_partial_satisfier(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
# c 2.0.0 is incompatible with y 2.0.0 because it requires x 1.0.0, but that
# requirement only exists because of both a and b. The solver should be able
@@ -68,7 +70,7 @@ def test_backjumps_after_partial_satisfier(
def test_rolls_back_leaf_versions_first(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
# The latest versions of a and b disagree on c. An older version of either
# will resolve the problem. This test validates that b, which is farther
@@ -85,9 +87,7 @@ def test_rolls_back_leaf_versions_first(
check_solver_result(root, provider, {"a": "2.0.0", "b": "1.0.0", "c": "2.0.0"})
-def test_simple_transitive(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
-):
+def test_simple_transitive(root: ProjectPackage, provider: Provider, repo: Repository):
# Only one version of baz, so foo and bar will have to downgrade
# until they reach it
root.add_dependency(Factory.create_dependency("foo", "*"))
@@ -108,7 +108,7 @@ def test_simple_transitive(
def test_backjump_to_nearer_unsatisfied_package(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
# This ensures it doesn't exhaustively search all versions of b when it's
# a-2.0.0 whose dependency on c-2.0.0-nonexistent led to the problem. We
@@ -130,7 +130,7 @@ def test_backjump_to_nearer_unsatisfied_package(
def test_traverse_into_package_with_fewer_versions_first(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
# Dependencies are ordered so that packages with fewer versions are tried
# first. Here, there are two valid solutions (either a or b must be
@@ -156,7 +156,7 @@ def test_traverse_into_package_with_fewer_versions_first(
def test_backjump_past_failed_package_on_disjoint_constraint(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("a", "*"))
root.add_dependency(Factory.create_dependency("foo", ">2.0.0"))
diff --git a/tests/mixology/version_solver/test_basic_graph.py b/tests/mixology/version_solver/test_basic_graph.py
index f0b95590ba0..9f392b2f26f 100644
--- a/tests/mixology/version_solver/test_basic_graph.py
+++ b/tests/mixology/version_solver/test_basic_graph.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.factory import Factory
@@ -12,7 +14,7 @@
def test_simple_dependencies(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("a", "1.0.0"))
root.add_dependency(Factory.create_dependency("b", "1.0.0"))
@@ -39,7 +41,7 @@ def test_simple_dependencies(
def test_shared_dependencies_with_overlapping_constraints(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("a", "1.0.0"))
root.add_dependency(Factory.create_dependency("b", "1.0.0"))
@@ -56,7 +58,7 @@ def test_shared_dependencies_with_overlapping_constraints(
def test_shared_dependency_where_dependent_version_affects_other_dependencies(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "<=1.0.2"))
root.add_dependency(Factory.create_dependency("bar", "1.0.0"))
@@ -76,7 +78,7 @@ def test_shared_dependency_where_dependent_version_affects_other_dependencies(
def test_circular_dependency(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "1.0.0"))
diff --git a/tests/mixology/version_solver/test_python_constraint.py b/tests/mixology/version_solver/test_python_constraint.py
index f5f4430e85b..f60e3a49293 100644
--- a/tests/mixology/version_solver/test_python_constraint.py
+++ b/tests/mixology/version_solver/test_python_constraint.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.factory import Factory
@@ -12,7 +14,7 @@
def test_dependency_does_not_match_root_python_constraint(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
provider.set_package_python_versions("^3.6")
root.add_dependency(Factory.create_dependency("foo", "*"))
diff --git a/tests/mixology/version_solver/test_unsolvable.py b/tests/mixology/version_solver/test_unsolvable.py
index fb8f58e06e4..072925e5507 100644
--- a/tests/mixology/version_solver/test_unsolvable.py
+++ b/tests/mixology/version_solver/test_unsolvable.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.factory import Factory
@@ -12,7 +14,7 @@
def test_no_version_matching_constraint(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "^1.0"))
@@ -30,7 +32,7 @@ def test_no_version_matching_constraint(
def test_no_version_that_matches_combined_constraints(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "1.0.0"))
root.add_dependency(Factory.create_dependency("bar", "1.0.0"))
@@ -53,7 +55,7 @@ def test_no_version_that_matches_combined_constraints(
def test_disjoint_constraints(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "1.0.0"))
root.add_dependency(Factory.create_dependency("bar", "1.0.0"))
@@ -75,7 +77,7 @@ def test_disjoint_constraints(
def test_disjoint_root_constraints(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "1.0.0"))
root.add_dependency(Factory.create_dependency("foo", "2.0.0"))
@@ -89,9 +91,7 @@ def test_disjoint_root_constraints(
check_solver_result(root, provider, error=error)
-def test_no_valid_solution(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
-):
+def test_no_valid_solution(root: ProjectPackage, provider: Provider, repo: Repository):
root.add_dependency(Factory.create_dependency("a", "*"))
root.add_dependency(Factory.create_dependency("b", "*"))
@@ -113,7 +113,7 @@ def test_no_valid_solution(
def test_package_with_the_same_name_gives_clear_error_message(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
pkg_name = "a"
root.add_dependency(Factory.create_dependency(pkg_name, "*"))
diff --git a/tests/mixology/version_solver/test_with_lock.py b/tests/mixology/version_solver/test_with_lock.py
index 5fd9dc5e83e..42b8d77fb53 100644
--- a/tests/mixology/version_solver/test_with_lock.py
+++ b/tests/mixology/version_solver/test_with_lock.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from poetry.factory import Factory
@@ -13,7 +15,7 @@
def test_with_compatible_locked_dependencies(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "*"))
@@ -33,7 +35,7 @@ def test_with_compatible_locked_dependencies(
def test_with_incompatible_locked_dependencies(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", ">1.0.1"))
@@ -53,7 +55,7 @@ def test_with_incompatible_locked_dependencies(
def test_with_unrelated_locked_dependencies(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "*"))
@@ -74,7 +76,7 @@ def test_with_unrelated_locked_dependencies(
def test_unlocks_dependencies_if_necessary_to_ensure_that_a_new_dependency_is_satisfied(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "*"))
root.add_dependency(Factory.create_dependency("newdep", "2.0.0"))
@@ -109,7 +111,7 @@ def test_unlocks_dependencies_if_necessary_to_ensure_that_a_new_dependency_is_sa
def test_with_compatible_locked_dependencies_use_latest(
- root: "ProjectPackage", provider: "Provider", repo: "Repository"
+ root: ProjectPackage, provider: Provider, repo: Repository
):
root.add_dependency(Factory.create_dependency("foo", "*"))
root.add_dependency(Factory.create_dependency("baz", "*"))
diff --git a/tests/packages/test_locker.py b/tests/packages/test_locker.py
index b6bb1837cc8..61213c59e26 100644
--- a/tests/packages/test_locker.py
+++ b/tests/packages/test_locker.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import logging
import tempfile
@@ -428,7 +430,7 @@ def test_locking_legacy_repository_package_should_include_source_section(
def test_locker_should_emit_warnings_if_lock_version_is_newer_but_allowed(
- locker: Locker, caplog: "LogCaptureFixture"
+ locker: Locker, caplog: LogCaptureFixture
):
version = ".".join(Version.parse(Locker._VERSION).next_minor().text.split(".")[:2])
content = f"""\
@@ -459,7 +461,7 @@ def test_locker_should_emit_warnings_if_lock_version_is_newer_but_allowed(
def test_locker_should_raise_an_error_if_lock_version_is_newer_and_not_allowed(
- locker: Locker, caplog: "LogCaptureFixture"
+ locker: Locker, caplog: LogCaptureFixture
):
content = """\
[metadata]
@@ -515,7 +517,7 @@ def test_extras_dependencies_are_ordered(locker: Locker, root: ProjectPackage):
def test_locker_should_neither_emit_warnings_nor_raise_error_for_lower_compatible_versions( # noqa: E501
- locker: Locker, caplog: "LogCaptureFixture"
+ locker: Locker, caplog: LogCaptureFixture
):
current_version = Version.parse(Locker._VERSION)
older_version = ".".join(
@@ -606,7 +608,7 @@ def test_locker_dumps_dependency_information_correctly(
def test_locked_repository_uses_root_dir_of_package(
- locker: Locker, mocker: "MockerFixture"
+ locker: Locker, mocker: MockerFixture
):
content = """\
[[package]]
diff --git a/tests/plugins/test_plugin_manager.py b/tests/plugins/test_plugin_manager.py
index 25d41b23c3c..2f7eb2f56a7 100644
--- a/tests/plugins/test_plugin_manager.py
+++ b/tests/plugins/test_plugin_manager.py
@@ -1,6 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import List
import pytest
@@ -37,7 +38,7 @@ def activate(self, poetry: Poetry, io: BufferedIO) -> None:
class MyCommandPlugin(ApplicationPlugin):
@property
- def commands(self) -> List[str]:
+ def commands(self) -> list[str]:
return []
@@ -48,7 +49,7 @@ def activate(self, poetry: Poetry, io: BufferedIO) -> None:
@pytest.fixture()
-def poetry(tmp_dir: str, config: "Config") -> Poetry:
+def poetry(tmp_dir: str, config: Config) -> Poetry:
poetry = Poetry(
CWD / "pyproject.toml",
{},
@@ -82,7 +83,7 @@ def test_load_plugins_and_activate(
manager_factory: ManagerFactory,
poetry: Poetry,
io: BufferedIO,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
):
manager = manager_factory()
@@ -104,7 +105,7 @@ def test_load_plugins_with_invalid_plugin(
manager_factory: ManagerFactory,
poetry: Poetry,
io: BufferedIO,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
):
manager = manager_factory()
@@ -125,7 +126,7 @@ def test_load_plugins_with_plugins_disabled(
no_plugin_manager: PluginManager,
poetry: Poetry,
io: BufferedIO,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
):
mocker.patch(
"entrypoints.get_group_all",
diff --git a/tests/publishing/test_publisher.py b/tests/publishing/test_publisher.py
index bbd0ea21b9b..1800365b55c 100644
--- a/tests/publishing/test_publisher.py
+++ b/tests/publishing/test_publisher.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
from pathlib import Path
@@ -20,7 +22,7 @@
def test_publish_publishes_to_pypi_by_default(
- fixture_dir: "FixtureDirGetter", mocker: "MockerFixture", config: "Config"
+ fixture_dir: FixtureDirGetter, mocker: MockerFixture, config: Config
):
uploader_auth = mocker.patch("poetry.publishing.uploader.Uploader.auth")
uploader_upload = mocker.patch("poetry.publishing.uploader.Uploader.upload")
@@ -42,9 +44,9 @@ def test_publish_publishes_to_pypi_by_default(
@pytest.mark.parametrize("fixture_name", ["sample_project", "with_default_source"])
def test_publish_can_publish_to_given_repository(
- fixture_dir: "FixtureDirGetter",
- mocker: "MockerFixture",
- config: "Config",
+ fixture_dir: FixtureDirGetter,
+ mocker: MockerFixture,
+ config: Config,
fixture_name: str,
):
uploader_auth = mocker.patch("poetry.publishing.uploader.Uploader.auth")
@@ -74,7 +76,7 @@ def test_publish_can_publish_to_given_repository(
def test_publish_raises_error_for_undefined_repository(
- fixture_dir: "FixtureDirGetter", config: "Config"
+ fixture_dir: FixtureDirGetter, config: Config
):
poetry = Factory().create_poetry(fixture_dir("sample_project"))
poetry._config = config
@@ -88,7 +90,7 @@ def test_publish_raises_error_for_undefined_repository(
def test_publish_uses_token_if_it_exists(
- fixture_dir: "FixtureDirGetter", mocker: "MockerFixture", config: "Config"
+ fixture_dir: FixtureDirGetter, mocker: MockerFixture, config: Config
):
uploader_auth = mocker.patch("poetry.publishing.uploader.Uploader.auth")
uploader_upload = mocker.patch("poetry.publishing.uploader.Uploader.upload")
@@ -107,7 +109,7 @@ def test_publish_uses_token_if_it_exists(
def test_publish_uses_cert(
- fixture_dir: "FixtureDirGetter", mocker: "MockerFixture", config: "Config"
+ fixture_dir: FixtureDirGetter, mocker: MockerFixture, config: Config
):
cert = "path/to/ca.pem"
uploader_auth = mocker.patch("poetry.publishing.uploader.Uploader.auth")
@@ -133,7 +135,7 @@ def test_publish_uses_cert(
def test_publish_uses_client_cert(
- fixture_dir: "FixtureDirGetter", mocker: "MockerFixture", config: "Config"
+ fixture_dir: FixtureDirGetter, mocker: MockerFixture, config: Config
):
client_cert = "path/to/client.pem"
uploader_upload = mocker.patch("poetry.publishing.uploader.Uploader.upload")
@@ -156,10 +158,10 @@ def test_publish_uses_client_cert(
def test_publish_read_from_environment_variable(
- fixture_dir: "FixtureDirGetter",
+ fixture_dir: FixtureDirGetter,
environ: None,
- mocker: "MockerFixture",
- config: "Config",
+ mocker: MockerFixture,
+ config: Config,
):
os.environ["POETRY_REPOSITORIES_FOO_URL"] = "https://foo.bar"
os.environ["POETRY_HTTP_BASIC_FOO_USERNAME"] = "bar"
diff --git a/tests/publishing/test_uploader.py b/tests/publishing/test_uploader.py
index 277fcfc3dcb..681dc8b8ddf 100644
--- a/tests/publishing/test_uploader.py
+++ b/tests/publishing/test_uploader.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Type
import pytest
@@ -19,12 +20,12 @@
@pytest.fixture
-def uploader(fixture_dir: "FixtureDirGetter") -> Uploader:
+def uploader(fixture_dir: FixtureDirGetter) -> Uploader:
return Uploader(Factory().create_poetry(fixture_dir("simple_project")), NullIO())
def test_uploader_properly_handles_400_errors(
- http: Type["httpretty.httpretty"], uploader: Uploader
+ http: type[httpretty.httpretty], uploader: Uploader
):
http.register_uri(http.POST, "https://foo.com", status=400, body="Bad request")
@@ -35,7 +36,7 @@ def test_uploader_properly_handles_400_errors(
def test_uploader_properly_handles_403_errors(
- http: Type["httpretty.httpretty"], uploader: Uploader
+ http: type[httpretty.httpretty], uploader: Uploader
):
http.register_uri(http.POST, "https://foo.com", status=403, body="Unauthorized")
@@ -46,7 +47,7 @@ def test_uploader_properly_handles_403_errors(
def test_uploader_properly_handles_301_redirects(
- http: Type["httpretty.httpretty"], uploader: Uploader
+ http: type[httpretty.httpretty], uploader: Uploader
):
http.register_uri(http.POST, "https://foo.com", status=301, body="Redirect")
@@ -60,7 +61,7 @@ def test_uploader_properly_handles_301_redirects(
def test_uploader_registers_for_appropriate_400_errors(
- mocker: "MockerFixture", http: Type["httpretty.httpretty"], uploader: Uploader
+ mocker: MockerFixture, http: type[httpretty.httpretty], uploader: Uploader
):
register = mocker.patch("poetry.publishing.uploader.Uploader._register")
http.register_uri(
diff --git a/tests/puzzle/conftest.py b/tests/puzzle/conftest.py
index 8df7f169a06..23bb4635ca0 100644
--- a/tests/puzzle/conftest.py
+++ b/tests/puzzle/conftest.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import shutil
from pathlib import Path
@@ -16,7 +18,7 @@
from pytest_mock import MockerFixture
-def mock_clone(self: "Git", source: str, dest: Path) -> None:
+def mock_clone(self: Git, source: str, dest: Path) -> None:
# Checking source to determine which folder we need to copy
parts = urlparse.urlparse(source)
@@ -33,7 +35,7 @@ def mock_clone(self: "Git", source: str, dest: Path) -> None:
@pytest.fixture(autouse=True)
-def setup(mocker: "MockerFixture") -> None:
+def setup(mocker: MockerFixture) -> None:
# Patch git module to not actually clone projects
mocker.patch("poetry.core.vcs.git.Git.clone", new=mock_clone)
mocker.patch("poetry.core.vcs.git.Git.checkout", new=lambda *_: None)
diff --git a/tests/puzzle/test_provider.py b/tests/puzzle/test_provider.py
index 6c625027c4c..3cb0df75074 100644
--- a/tests/puzzle/test_provider.py
+++ b/tests/puzzle/test_provider.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from pathlib import Path
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
@@ -98,7 +100,7 @@ def test_search_for_vcs_setup_egg_info_with_extras(provider: Provider):
}
-def test_search_for_vcs_read_setup(provider: Provider, mocker: "MockerFixture"):
+def test_search_for_vcs_read_setup(provider: Provider, mocker: MockerFixture):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv())
dependency = VCSDependency("demo", "git", "https://github.com/demo/demo.git")
@@ -119,7 +121,7 @@ def test_search_for_vcs_read_setup(provider: Provider, mocker: "MockerFixture"):
def test_search_for_vcs_read_setup_with_extras(
- provider: Provider, mocker: "MockerFixture"
+ provider: Provider, mocker: MockerFixture
):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv())
@@ -139,7 +141,7 @@ def test_search_for_vcs_read_setup_with_extras(
def test_search_for_vcs_read_setup_raises_error_if_no_version(
- provider: Provider, mocker: "MockerFixture"
+ provider: Provider, mocker: MockerFixture
):
mocker.patch(
"poetry.inspection.info.PackageInfo._pep517_metadata",
@@ -248,7 +250,7 @@ def test_search_for_directory_setup_with_base(provider: Provider, directory: str
def test_search_for_directory_setup_read_setup(
- provider: Provider, mocker: "MockerFixture"
+ provider: Provider, mocker: MockerFixture
):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv())
@@ -278,7 +280,7 @@ def test_search_for_directory_setup_read_setup(
def test_search_for_directory_setup_read_setup_with_extras(
- provider: Provider, mocker: "MockerFixture"
+ provider: Provider, mocker: MockerFixture
):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv())
diff --git a/tests/puzzle/test_solver.py b/tests/puzzle/test_solver.py
index 92e5e817837..d3242cfb531 100644
--- a/tests/puzzle/test_solver.py
+++ b/tests/puzzle/test_solver.py
@@ -1,10 +1,8 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Optional
-from typing import Type
import pytest
@@ -93,10 +91,10 @@ def solver(
def check_solver_result(
- transaction: "Transaction",
- expected: List[Dict[str, Any]],
+ transaction: Transaction,
+ expected: list[dict[str, Any]],
synchronize: bool = False,
-) -> List["OperationTypes"]:
+) -> list[OperationTypes]:
for e in expected:
if "skipped" not in e:
e["skipped"] = False
@@ -523,7 +521,7 @@ def test_solver_returns_extras_only_requested(
solver: Solver,
repo: Repository,
package: ProjectPackage,
- enabled_extra: Optional[bool],
+ enabled_extra: bool | None,
):
extras = [enabled_extra] if enabled_extra is not None else []
@@ -585,7 +583,7 @@ def test_solver_returns_extras_when_multiple_extras_use_same_dependency(
solver: Solver,
repo: Repository,
package: ProjectPackage,
- enabled_extra: Optional[bool],
+ enabled_extra: bool | None,
):
package.add_dependency(Factory.create_dependency("A", "*"))
@@ -634,7 +632,7 @@ def test_solver_returns_extras_only_requested_nested(
solver: Solver,
repo: Repository,
package: ProjectPackage,
- enabled_extra: Optional[bool],
+ enabled_extra: bool | None,
):
package.add_dependency(Factory.create_dependency("A", "*"))
@@ -1432,7 +1430,7 @@ def test_solver_can_resolve_git_dependencies_with_extras(
ids=["branch", "tag", "rev"],
)
def test_solver_can_resolve_git_dependencies_with_ref(
- solver: Solver, repo: Repository, package: Package, ref: Dict[str, str]
+ solver: Solver, repo: Repository, package: Package, ref: dict[str, str]
):
pendulum = get_package("pendulum", "2.0.3")
cleo = get_package("cleo", "1.0.0")
@@ -2771,7 +2769,7 @@ def test_solver_cannot_choose_another_version_for_url_dependencies(
solver: Solver,
repo: Repository,
package: Package,
- http: Type["httpretty.httpretty"],
+ http: type[httpretty.httpretty],
):
path = (
Path(__file__).parent.parent
diff --git a/tests/puzzle/test_transaction.py b/tests/puzzle/test_transaction.py
index fbc73cfdd96..6db7f2c13d2 100644
--- a/tests/puzzle/test_transaction.py
+++ b/tests/puzzle/test_transaction.py
@@ -1,7 +1,7 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
from poetry.core.packages.package import Package
@@ -12,9 +12,7 @@
from poetry.installation.operations import OperationTypes
-def check_operations(
- ops: List["OperationTypes"], expected: List[Dict[str, Any]]
-) -> None:
+def check_operations(ops: list[OperationTypes], expected: list[dict[str, Any]]) -> None:
for e in expected:
if "skipped" not in e:
e["skipped"] = False
diff --git a/tests/repositories/test_installed_repository.py b/tests/repositories/test_installed_repository.py
index 82f2038c6d2..3230bf5317e 100644
--- a/tests/repositories/test_installed_repository.py
+++ b/tests/repositories/test_installed_repository.py
@@ -1,8 +1,7 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import List
-from typing import Optional
import pytest
@@ -46,14 +45,14 @@
class MockEnv(BaseMockEnv):
@property
- def paths(self) -> Dict[str, Path]:
+ def paths(self) -> dict[str, Path]:
return {
"purelib": SITE_PURELIB,
"platlib": SITE_PLATLIB,
}
@property
- def sys_path(self) -> List[Path]:
+ def sys_path(self) -> list[Path]:
return [ENV_DIR, SITE_PLATLIB, SITE_PURELIB]
@@ -63,7 +62,7 @@ def env() -> MockEnv:
@pytest.fixture
-def repository(mocker: "MockerFixture", env: MockEnv) -> InstalledRepository:
+def repository(mocker: MockerFixture, env: MockEnv) -> InstalledRepository:
mocker.patch(
"poetry.utils._compat.metadata.Distribution.discover",
return_value=INSTALLED_RESULTS,
@@ -85,7 +84,7 @@ def repository(mocker: "MockerFixture", env: MockEnv) -> InstalledRepository:
def get_package_from_repository(
name: str, repository: InstalledRepository
-) -> Optional["Package"]:
+) -> Package | None:
for pkg in repository.packages:
if pkg.name == name:
return pkg
diff --git a/tests/repositories/test_legacy_repository.py b/tests/repositories/test_legacy_repository.py
index 482e75d61bc..607e8d87d3c 100644
--- a/tests/repositories/test_legacy_repository.py
+++ b/tests/repositories/test_legacy_repository.py
@@ -1,10 +1,9 @@
+from __future__ import annotations
+
import shutil
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import Optional
-from typing import Type
import pytest
import requests
@@ -36,7 +35,7 @@ class MockRepository(LegacyRepository):
def __init__(self) -> None:
super().__init__("legacy", url="http://legacy.foo.bar", disable_cache=True)
- def _get_page(self, endpoint: str) -> Optional[Page]:
+ def _get_page(self, endpoint: str) -> Page | None:
parts = endpoint.split("/")
name = parts[1]
@@ -331,7 +330,7 @@ def test_get_package_retrieves_packages_with_no_hashes():
class MockHttpRepository(LegacyRepository):
- def __init__(self, endpoint_responses: Dict, http: Type["httpretty.httpretty"]):
+ def __init__(self, endpoint_responses: dict, http: type[httpretty.httpretty]):
base_url = "http://legacy.foo.bar"
super().__init__("legacy", url=base_url, disable_cache=True)
@@ -340,20 +339,20 @@ def __init__(self, endpoint_responses: Dict, http: Type["httpretty.httpretty"]):
http.register_uri(http.GET, url, status=response)
-def test_get_200_returns_page(http: Type["httpretty.httpretty"]):
+def test_get_200_returns_page(http: type[httpretty.httpretty]):
repo = MockHttpRepository({"/foo": 200}, http)
assert repo._get_page("/foo")
@pytest.mark.parametrize("status_code", [401, 403, 404])
-def test_get_40x_and_returns_none(http: Type["httpretty.httpretty"], status_code: int):
+def test_get_40x_and_returns_none(http: type[httpretty.httpretty], status_code: int):
repo = MockHttpRepository({"/foo": status_code}, http)
assert repo._get_page("/foo") is None
-def test_get_5xx_raises(http: Type["httpretty.httpretty"]):
+def test_get_5xx_raises(http: type[httpretty.httpretty]):
repo = MockHttpRepository({"/foo": 500}, http)
with pytest.raises(RepositoryError):
@@ -361,7 +360,7 @@ def test_get_5xx_raises(http: Type["httpretty.httpretty"]):
def test_get_redirected_response_url(
- http: Type["httpretty.httpretty"], monkeypatch: "MonkeyPatch"
+ http: type[httpretty.httpretty], monkeypatch: MonkeyPatch
):
repo = MockHttpRepository({"/foo": 200}, http)
redirect_url = "http://legacy.redirect.bar"
diff --git a/tests/repositories/test_pool.py b/tests/repositories/test_pool.py
index 21eb59f4a89..9d2b77ac241 100644
--- a/tests/repositories/test_pool.py
+++ b/tests/repositories/test_pool.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import pytest
from poetry.repositories import Pool
diff --git a/tests/repositories/test_pypi_repository.py b/tests/repositories/test_pypi_repository.py
index 24b1b67a793..6b30dc46ad3 100644
--- a/tests/repositories/test_pypi_repository.py
+++ b/tests/repositories/test_pypi_repository.py
@@ -1,11 +1,11 @@
+from __future__ import annotations
+
import json
import shutil
from io import BytesIO
from pathlib import Path
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import Optional
import pytest
@@ -30,7 +30,7 @@ class MockRepository(PyPiRepository):
def __init__(self, fallback: bool = False):
super().__init__(url="http://foo.bar", disable_cache=True, fallback=fallback)
- def _get(self, url: str) -> Optional[Dict]:
+ def _get(self, url: str) -> dict | None:
parts = url.split("/")[1:]
name = parts[0]
if len(parts) == 3:
@@ -214,7 +214,7 @@ def test_invalid_versions_ignored():
assert len(packages) == 1
-def test_get_should_invalid_cache_on_too_many_redirects_error(mocker: "MockerFixture"):
+def test_get_should_invalid_cache_on_too_many_redirects_error(mocker: MockerFixture):
delete_cache = mocker.patch("cachecontrol.caches.file_cache.FileCache.delete")
response = Response()
diff --git a/tests/test_factory.py b/tests/test_factory.py
index 6afa0226a6f..8c623cc5932 100644
--- a/tests/test_factory.py
+++ b/tests/test_factory.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
@@ -24,7 +26,7 @@
class MyPlugin(Plugin):
- def activate(self, poetry: "Poetry", io: "IO") -> None:
+ def activate(self, poetry: Poetry, io: IO) -> None:
io.write_line("Updating version")
poetry.package.set_version("9.9.9")
@@ -291,7 +293,7 @@ def test_create_poetry_fails_on_invalid_configuration():
assert str(e.value) == expected
-def test_create_poetry_with_local_config(fixture_dir: "FixtureDirGetter"):
+def test_create_poetry_with_local_config(fixture_dir: FixtureDirGetter):
poetry = Factory().create_poetry(fixture_dir("with_local_config"))
assert not poetry.config.get("virtualenvs.in-project")
@@ -300,7 +302,7 @@ def test_create_poetry_with_local_config(fixture_dir: "FixtureDirGetter"):
assert not poetry.config.get("virtualenvs.options.system-site-packages")
-def test_create_poetry_with_plugins(mocker: "MockerFixture"):
+def test_create_poetry_with_plugins(mocker: MockerFixture):
mocker.patch(
"entrypoints.get_group_all",
return_value=[EntryPoint("my-plugin", "tests.test_factory", "MyPlugin")],
diff --git a/tests/types.py b/tests/types.py
index a44666da1ab..34a974df646 100644
--- a/tests/types.py
+++ b/tests/types.py
@@ -1,6 +1,6 @@
+from __future__ import annotations
+
from typing import TYPE_CHECKING
-from typing import Dict
-from typing import Optional
from tests.compat import Protocol
@@ -23,34 +23,32 @@ class CommandTesterFactory(Protocol):
def __call__(
self,
command: str,
- poetry: Optional["Poetry"] = None,
- installer: Optional["Installer"] = None,
- executor: Optional["Executor"] = None,
- environment: Optional["Env"] = None,
- ) -> "CommandTester":
+ poetry: Poetry | None = None,
+ installer: Installer | None = None,
+ executor: Executor | None = None,
+ environment: Env | None = None,
+ ) -> CommandTester:
...
class SourcesFactory(Protocol):
- def __call__(
- self, poetry: "Poetry", sources: "Source", config: "Config", io: "IO"
- ) -> None:
+ def __call__(self, poetry: Poetry, sources: Source, config: Config, io: IO) -> None:
...
class ProjectFactory(Protocol):
def __call__(
self,
- name: Optional[str] = None,
- dependencies: Optional[Dict[str, str]] = None,
- dev_dependencies: Optional[Dict[str, str]] = None,
- pyproject_content: Optional[str] = None,
- poetry_lock_content: Optional[str] = None,
+ name: str | None = None,
+ dependencies: dict[str, str] | None = None,
+ dev_dependencies: dict[str, str] | None = None,
+ pyproject_content: str | None = None,
+ poetry_lock_content: str | None = None,
install_deps: bool = True,
- ) -> "Poetry":
+ ) -> Poetry:
...
class FixtureDirGetter(Protocol):
- def __call__(self, name: str) -> "Path":
+ def __call__(self, name: str) -> Path:
...
diff --git a/tests/utils/fixtures/setups/ansible/setup.py b/tests/utils/fixtures/setups/ansible/setup.py
index 8216f154257..3bebf1c3b9a 100644
--- a/tests/utils/fixtures/setups/ansible/setup.py
+++ b/tests/utils/fixtures/setups/ansible/setup.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import json
import os
import os.path
@@ -9,8 +11,10 @@
from distutils.command.build_scripts import build_scripts as BuildScripts
from distutils.command.sdist import sdist as SDist
+
try:
- from setuptools import setup, find_packages
+ from setuptools import find_packages
+ from setuptools import setup
from setuptools.command.build_py import build_py as BuildPy
from setuptools.command.install_lib import install_lib as InstallLib
from setuptools.command.install_scripts import install_scripts as InstallScripts
@@ -24,7 +28,8 @@
sys.exit(1)
sys.path.insert(0, os.path.abspath("lib"))
-from ansible.release import __version__, __author__
+from ansible.release import __author__
+from ansible.release import __version__
SYMLINK_CACHE = "SYMLINK_CACHE.json"
diff --git a/tests/utils/fixtures/setups/extras_require_with_vars/setup.py b/tests/utils/fixtures/setups/extras_require_with_vars/setup.py
index 5d7962dfebf..e40db81d327 100644
--- a/tests/utils/fixtures/setups/extras_require_with_vars/setup.py
+++ b/tests/utils/fixtures/setups/extras_require_with_vars/setup.py
@@ -1,5 +1,8 @@
+from __future__ import annotations
+
from setuptools import setup
+
tests_require = ["pytest"]
setup(
diff --git a/tests/utils/fixtures/setups/flask/setup.py b/tests/utils/fixtures/setups/flask/setup.py
index 82bd906f8f6..74a059deed6 100644
--- a/tests/utils/fixtures/setups/flask/setup.py
+++ b/tests/utils/fixtures/setups/flask/setup.py
@@ -1,10 +1,13 @@
#!/usr/bin/env python
-import io
+from __future__ import annotations
+
import re
+
from collections import OrderedDict
from setuptools import setup
+
with open("README.rst", encoding="utf8") as f:
readme = f.read()
diff --git a/tests/utils/fixtures/setups/pendulum/setup.py b/tests/utils/fixtures/setups/pendulum/setup.py
index 4dcbe961465..d0af694c887 100644
--- a/tests/utils/fixtures/setups/pendulum/setup.py
+++ b/tests/utils/fixtures/setups/pendulum/setup.py
@@ -1,7 +1,10 @@
+from __future__ import annotations
+
from distutils.core import setup
from build import *
+
packages = [
"pendulum",
"pendulum._extensions",
diff --git a/tests/utils/fixtures/setups/pyyaml/setup.py b/tests/utils/fixtures/setups/pyyaml/setup.py
index 61191324350..ce865368d2a 100644
--- a/tests/utils/fixtures/setups/pyyaml/setup.py
+++ b/tests/utils/fixtures/setups/pyyaml/setup.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+
NAME = "PyYAML"
VERSION = "3.13"
DESCRIPTION = "YAML parser and emitter for Python"
@@ -53,21 +56,23 @@
"""
-import sys, os.path, platform
+import os.path
+import platform
+import sys
from distutils import log
-from distutils.core import setup, Command
+from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
+from distutils.command.build_ext import build_ext as _build_ext
+from distutils.core import Command
from distutils.core import Distribution as _Distribution
from distutils.core import Extension as _Extension
+from distutils.core import setup
from distutils.dir_util import mkpath
-from distutils.command.build_ext import build_ext as _build_ext
-from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
-from distutils.errors import (
- DistutilsError,
- CompileError,
- LinkError,
- DistutilsPlatformError,
-)
+from distutils.errors import CompileError
+from distutils.errors import DistutilsError
+from distutils.errors import DistutilsPlatformError
+from distutils.errors import LinkError
+
if "setuptools.extension" in sys.modules:
_Extension = sys.modules["setuptools.extension"]._Extension
@@ -77,8 +82,8 @@
with_cython = False
try:
- from Cython.Distutils.extension import Extension as _Extension
from Cython.Distutils import build_ext as _build_ext
+ from Cython.Distutils.extension import Extension as _Extension
with_cython = True
except ImportError:
diff --git a/tests/utils/fixtures/setups/requests/setup.py b/tests/utils/fixtures/setups/requests/setup.py
index 0591adb81cb..e8c2df313b1 100644
--- a/tests/utils/fixtures/setups/requests/setup.py
+++ b/tests/utils/fixtures/setups/requests/setup.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python
# Learn more: https://github.com/kennethreitz/setup.py
+from __future__ import annotations
+
import os
-import re
import sys
from codecs import open
@@ -9,6 +10,7 @@
from setuptools import setup
from setuptools.command.test import test as TestCommand
+
here = os.path.abspath(os.path.dirname(__file__))
diff --git a/tests/utils/fixtures/setups/setuptools_setup/setup.py b/tests/utils/fixtures/setups/setuptools_setup/setup.py
index 807d8c702fe..c8e0dafe38c 100644
--- a/tests/utils/fixtures/setups/setuptools_setup/setup.py
+++ b/tests/utils/fixtures/setups/setuptools_setup/setup.py
@@ -1,5 +1,8 @@
+from __future__ import annotations
+
import setuptools
+
setuptools.setup(
name="my_package",
version="0.1.2",
diff --git a/tests/utils/fixtures/setups/sqlalchemy/setup.py b/tests/utils/fixtures/setups/sqlalchemy/setup.py
index bc367a1d5d0..b44d21509e4 100644
--- a/tests/utils/fixtures/setups/sqlalchemy/setup.py
+++ b/tests/utils/fixtures/setups/sqlalchemy/setup.py
@@ -1,16 +1,22 @@
+from __future__ import annotations
+
import os
import platform
import re
import sys
+
from distutils.command.build_ext import build_ext
from distutils.errors import CCompilerError
from distutils.errors import DistutilsExecError
from distutils.errors import DistutilsPlatformError
-from setuptools import Distribution as _Distribution, Extension
-from setuptools import setup
+
+from setuptools import Distribution as _Distribution
+from setuptools import Extension
from setuptools import find_packages
+from setuptools import setup
from setuptools.command.test import test as TestCommand
+
cmdclass = {}
cpython = platform.python_implementation() == "CPython"
diff --git a/tests/utils/fixtures/setups/with-setup-cfg-attr/setup.py b/tests/utils/fixtures/setups/with-setup-cfg-attr/setup.py
index 606849326a4..536cf1785ef 100644
--- a/tests/utils/fixtures/setups/with-setup-cfg-attr/setup.py
+++ b/tests/utils/fixtures/setups/with-setup-cfg-attr/setup.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
from setuptools import setup
+
setup()
diff --git a/tests/utils/fixtures/setups/with-setup-cfg/setup.py b/tests/utils/fixtures/setups/with-setup-cfg/setup.py
index 606849326a4..536cf1785ef 100644
--- a/tests/utils/fixtures/setups/with-setup-cfg/setup.py
+++ b/tests/utils/fixtures/setups/with-setup-cfg/setup.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
from setuptools import setup
+
setup()
diff --git a/tests/utils/test_authenticator.py b/tests/utils/test_authenticator.py
index cf41f4f6a87..25b312211b7 100644
--- a/tests/utils/test_authenticator.py
+++ b/tests/utils/test_authenticator.py
@@ -1,13 +1,11 @@
+from __future__ import annotations
+
import re
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
-from typing import List
-from typing import Type
-from typing import Union
import httpretty
import pytest
@@ -33,7 +31,7 @@ class SimpleCredential:
@pytest.fixture()
-def mock_remote(http: Type[httpretty.httpretty]) -> None:
+def mock_remote(http: type[httpretty.httpretty]) -> None:
http.register_uri(
http.GET,
re.compile("^https?://foo.bar/(.+?)$"),
@@ -41,7 +39,7 @@ def mock_remote(http: Type[httpretty.httpretty]) -> None:
def test_authenticator_uses_url_provided_credentials(
- config: "Config", mock_remote: None, http: Type[httpretty.httpretty]
+ config: Config, mock_remote: None, http: type[httpretty.httpretty]
):
config.merge(
{
@@ -59,7 +57,7 @@ def test_authenticator_uses_url_provided_credentials(
def test_authenticator_uses_credentials_from_config_if_not_provided(
- config: "Config", mock_remote: None, http: Type[httpretty.httpretty]
+ config: Config, mock_remote: None, http: type[httpretty.httpretty]
):
config.merge(
{
@@ -77,9 +75,9 @@ def test_authenticator_uses_credentials_from_config_if_not_provided(
def test_authenticator_uses_username_only_credentials(
- config: "Config",
+ config: Config,
mock_remote: None,
- http: Type[httpretty.httpretty],
+ http: type[httpretty.httpretty],
with_simple_keyring: None,
):
config.merge(
@@ -98,7 +96,7 @@ def test_authenticator_uses_username_only_credentials(
def test_authenticator_uses_password_only_credentials(
- config: "Config", mock_remote: None, http: Type[httpretty.httpretty]
+ config: Config, mock_remote: None, http: type[httpretty.httpretty]
):
config.merge(
{
@@ -116,9 +114,9 @@ def test_authenticator_uses_password_only_credentials(
def test_authenticator_uses_empty_strings_as_default_password(
- config: "Config",
+ config: Config,
mock_remote: None,
- http: Type[httpretty.httpretty],
+ http: type[httpretty.httpretty],
with_simple_keyring: None,
):
config.merge(
@@ -137,7 +135,7 @@ def test_authenticator_uses_empty_strings_as_default_password(
def test_authenticator_uses_empty_strings_as_default_username(
- config: "Config", mock_remote: None, http: Type[httpretty.httpretty]
+ config: Config, mock_remote: None, http: type[httpretty.httpretty]
):
config.merge(
{
@@ -155,11 +153,11 @@ def test_authenticator_uses_empty_strings_as_default_username(
def test_authenticator_falls_back_to_keyring_url(
- config: "Config",
+ config: Config,
mock_remote: None,
- http: Type[httpretty.httpretty],
+ http: type[httpretty.httpretty],
with_simple_keyring: None,
- dummy_keyring: "DummyBackend",
+ dummy_keyring: DummyBackend,
):
config.merge(
{
@@ -180,11 +178,11 @@ def test_authenticator_falls_back_to_keyring_url(
def test_authenticator_falls_back_to_keyring_netloc(
- config: "Config",
+ config: Config,
mock_remote: None,
- http: Type[httpretty.httpretty],
+ http: type[httpretty.httpretty],
with_simple_keyring: None,
- dummy_keyring: "DummyBackend",
+ dummy_keyring: DummyBackend,
):
config.merge(
{
@@ -204,7 +202,7 @@ def test_authenticator_falls_back_to_keyring_netloc(
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")
def test_authenticator_request_retries_on_exception(
- mocker: "MockerFixture", config: "Config", http: Type[httpretty.httpretty]
+ mocker: MockerFixture, config: Config, http: type[httpretty.httpretty]
):
sleep = mocker.patch("time.sleep")
sdist_uri = f"https://foo.bar/files/{uuid.uuid4()!s}/foo-0.1.0.tar.gz"
@@ -212,8 +210,8 @@ def test_authenticator_request_retries_on_exception(
seen = []
def callback(
- request: requests.Request, uri: str, response_headers: Dict
- ) -> List[Union[int, Dict, str]]:
+ request: requests.Request, uri: str, response_headers: dict
+ ) -> list[int | dict | str]:
if seen.count(uri) < 2:
seen.append(uri)
raise requests.exceptions.ConnectionError("Disconnected")
@@ -229,7 +227,7 @@ def callback(
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")
def test_authenticator_request_raises_exception_when_attempts_exhausted(
- mocker: "MockerFixture", config: "Config", http: Type[httpretty.httpretty]
+ mocker: MockerFixture, config: Config, http: type[httpretty.httpretty]
):
sleep = mocker.patch("time.sleep")
sdist_uri = f"https://foo.bar/files/{uuid.uuid4()!s}/foo-0.1.0.tar.gz"
@@ -260,9 +258,9 @@ def callback(*_: Any, **___: Any) -> None:
],
)
def test_authenticator_request_retries_on_status_code(
- mocker: "MockerFixture",
- config: "Config",
- http: Type[httpretty.httpretty],
+ mocker: MockerFixture,
+ config: Config,
+ http: type[httpretty.httpretty],
status: int,
attempts: int,
):
@@ -271,8 +269,8 @@ def test_authenticator_request_retries_on_status_code(
content = str(uuid.uuid4())
def callback(
- request: requests.Request, uri: str, response_headers: Dict
- ) -> List[Union[int, Dict, str]]:
+ request: requests.Request, uri: str, response_headers: dict
+ ) -> list[int | dict | str]:
return [status, response_headers, content]
httpretty.register_uri(httpretty.GET, sdist_uri, body=callback)
@@ -288,16 +286,16 @@ def callback(
@pytest.fixture
-def environment_repository_credentials(monkeypatch: "MonkeyPatch") -> None:
+def environment_repository_credentials(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_USERNAME", "bar")
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_PASSWORD", "baz")
def test_authenticator_uses_env_provided_credentials(
- config: "Config",
+ config: Config,
environ: None,
- mock_remote: Type[httpretty.httpretty],
- http: Type[httpretty.httpretty],
+ mock_remote: type[httpretty.httpretty],
+ http: type[httpretty.httpretty],
environment_repository_credentials: None,
):
config.merge({"repositories": {"foo": {"url": "https://foo.bar/simple/"}}})
diff --git a/tests/utils/test_env.py b/tests/utils/test_env.py
index 08702e1c4e0..5e4ebef1ace 100644
--- a/tests/utils/test_env.py
+++ b/tests/utils/test_env.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import shutil
import subprocess
@@ -8,9 +10,6 @@
from typing import Any
from typing import Callable
from typing import Iterator
-from typing import List
-from typing import Optional
-from typing import Union
import pytest
import tomlkit
@@ -53,15 +52,15 @@ class MockVirtualEnv(VirtualEnv):
def __init__(
self,
path: Path,
- base: Optional[Path] = None,
- sys_path: Optional[List[str]] = None,
+ base: Path | None = None,
+ sys_path: list[str] | None = None,
):
super().__init__(path, base=base)
self._sys_path = sys_path
@property
- def sys_path(self) -> Optional[List[str]]:
+ def sys_path(self) -> list[str] | None:
if self._sys_path is not None:
return self._sys_path
@@ -69,7 +68,7 @@ def sys_path(self) -> Optional[List[str]]:
@pytest.fixture()
-def poetry(config: "Config") -> "Poetry":
+def poetry(config: Config) -> Poetry:
poetry = Factory().create_poetry(
Path(__file__).parent.parent / "fixtures" / "simple_project"
)
@@ -79,7 +78,7 @@ def poetry(config: "Config") -> "Poetry":
@pytest.fixture()
-def manager(poetry: "Poetry") -> EnvManager:
+def manager(poetry: Poetry) -> EnvManager:
return EnvManager(poetry)
@@ -120,7 +119,7 @@ def test_env_shell_commands_with_stdinput_in_their_arg_work_as_expected(
@pytest.fixture
-def in_project_venv_dir(poetry: "Poetry") -> Iterator[Path]:
+def in_project_venv_dir(poetry: Poetry) -> Iterator[Path]:
os.environ.pop("VIRTUAL_ENV", None)
venv_dir = poetry.file.parent.joinpath(".venv")
venv_dir.mkdir()
@@ -133,9 +132,9 @@ def in_project_venv_dir(poetry: "Poetry") -> Iterator[Path]:
@pytest.mark.parametrize("in_project", [True, False, None])
def test_env_get_venv_with_venv_folder_present(
manager: EnvManager,
- poetry: "Poetry",
+ poetry: Poetry,
in_project_venv_dir: Path,
- in_project: Optional[bool],
+ in_project: bool | None,
):
poetry.config.config["virtualenvs"]["in-project"] = in_project
venv = manager.get()
@@ -145,7 +144,7 @@ def test_env_get_venv_with_venv_folder_present(
assert venv.path == in_project_venv_dir
-def build_venv(path: Union[Path, str], **__: Any) -> None:
+def build_venv(path: Path | str, **__: Any) -> None:
os.mkdir(str(path))
@@ -171,9 +170,9 @@ def check_output(cmd: str, *args: Any, **kwargs: Any) -> str:
def test_activate_activates_non_existing_virtualenv_no_envs_file(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -215,9 +214,9 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file(
def test_activate_activates_existing_virtualenv_no_envs_file(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -255,9 +254,9 @@ def test_activate_activates_existing_virtualenv_no_envs_file(
def test_activate_activates_same_virtualenv_with_envs_file(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -299,9 +298,9 @@ def test_activate_activates_same_virtualenv_with_envs_file(
def test_activate_activates_different_virtualenv_with_envs_file(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -349,9 +348,9 @@ def test_activate_activates_different_virtualenv_with_envs_file(
def test_activate_activates_recreates_for_different_patch(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -412,9 +411,9 @@ def test_activate_activates_recreates_for_different_patch(
def test_activate_does_not_recreate_when_switching_minor(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -463,9 +462,9 @@ def test_activate_does_not_recreate_when_switching_minor(
def test_deactivate_non_activated_but_existing(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -492,9 +491,9 @@ def test_deactivate_non_activated_but_existing(
def test_deactivate_activated(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -535,9 +534,9 @@ def test_deactivate_activated(
def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
os.environ["VIRTUAL_ENV"] = "/environment/prefix"
@@ -566,7 +565,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
assert env.base == Path("/prefix")
-def test_list(tmp_dir: str, manager: EnvManager, poetry: "Poetry", config: "Config"):
+def test_list(tmp_dir: str, manager: EnvManager, poetry: Poetry, config: Config):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
@@ -583,9 +582,9 @@ def test_list(tmp_dir: str, manager: EnvManager, poetry: "Poetry", config: "Conf
def test_remove_by_python_version(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
@@ -608,9 +607,9 @@ def test_remove_by_python_version(
def test_remove_by_name(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
@@ -633,9 +632,9 @@ def test_remove_by_name(
def test_remove_also_deactivates(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
@@ -666,9 +665,9 @@ def test_remove_also_deactivates(
def test_remove_keeps_dir_if_not_deleteable(
tmp_dir: str,
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
):
# Ensure we empty rather than delete folder if its is an active mount point.
# See https://github.com/python-poetry/poetry/pull/2064
@@ -737,7 +736,7 @@ def test_run_with_input_non_zero_return(tmp_dir: str, tmp_venv: VirtualEnv):
def test_run_with_keyboard_interrupt(
- tmp_dir: str, tmp_venv: VirtualEnv, mocker: "MockerFixture"
+ tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch("subprocess.run", side_effect=KeyboardInterrupt())
with pytest.raises(KeyboardInterrupt):
@@ -746,7 +745,7 @@ def test_run_with_keyboard_interrupt(
def test_call_with_input_and_keyboard_interrupt(
- tmp_dir: str, tmp_venv: VirtualEnv, mocker: "MockerFixture"
+ tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch("subprocess.run", side_effect=KeyboardInterrupt())
kwargs = {"call": True}
@@ -756,7 +755,7 @@ def test_call_with_input_and_keyboard_interrupt(
def test_call_no_input_with_keyboard_interrupt(
- tmp_dir: str, tmp_venv: VirtualEnv, mocker: "MockerFixture"
+ tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch("subprocess.call", side_effect=KeyboardInterrupt())
kwargs = {"call": True}
@@ -766,7 +765,7 @@ def test_call_no_input_with_keyboard_interrupt(
def test_run_with_called_process_error(
- tmp_dir: str, tmp_venv: VirtualEnv, mocker: "MockerFixture"
+ tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch(
"subprocess.run", side_effect=subprocess.CalledProcessError(42, "some_command")
@@ -777,7 +776,7 @@ def test_run_with_called_process_error(
def test_call_with_input_and_called_process_error(
- tmp_dir: str, tmp_venv: VirtualEnv, mocker: "MockerFixture"
+ tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch(
"subprocess.run", side_effect=subprocess.CalledProcessError(42, "some_command")
@@ -789,7 +788,7 @@ def test_call_with_input_and_called_process_error(
def test_call_no_input_with_called_process_error(
- tmp_dir: str, tmp_venv: VirtualEnv, mocker: "MockerFixture"
+ tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch(
"subprocess.call", side_effect=subprocess.CalledProcessError(42, "some_command")
@@ -802,9 +801,9 @@ def test_call_no_input_with_called_process_error(
def test_create_venv_tries_to_find_a_compatible_python_executable_using_generic_ones_first( # noqa: E501
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
@@ -836,9 +835,9 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_generic_
def test_create_venv_tries_to_find_a_compatible_python_executable_using_specific_ones(
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
@@ -866,7 +865,7 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_specific
def test_create_venv_fails_if_no_compatible_python_version_could_be_found(
- manager: EnvManager, poetry: "Poetry", config: "Config", mocker: "MockerFixture"
+ manager: EnvManager, poetry: Poetry, config: Config, mocker: MockerFixture
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -892,7 +891,7 @@ def test_create_venv_fails_if_no_compatible_python_version_could_be_found(
def test_create_venv_does_not_try_to_find_compatible_versions_with_executable(
- manager: EnvManager, poetry: "Poetry", config: "Config", mocker: "MockerFixture"
+ manager: EnvManager, poetry: Poetry, config: Config, mocker: MockerFixture
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -919,9 +918,9 @@ def test_create_venv_does_not_try_to_find_compatible_versions_with_executable(
def test_create_venv_uses_patch_version_to_detect_compatibility(
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
@@ -957,9 +956,9 @@ def test_create_venv_uses_patch_version_to_detect_compatibility(
def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable(
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
@@ -996,10 +995,10 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable(
def test_activate_with_in_project_setting_does_not_fail_if_no_venvs_dir(
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
+ poetry: Poetry,
+ config: Config,
tmp_dir: str,
- mocker: "MockerFixture",
+ mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
@@ -1053,7 +1052,7 @@ def test_system_env_has_correct_paths():
"enabled",
[True, False],
)
-def test_system_env_usersite(mocker: "MockerFixture", enabled: bool):
+def test_system_env_usersite(mocker: MockerFixture, enabled: bool):
mocker.patch("site.check_enableusersite", return_value=enabled)
env = SystemEnv(Path(sys.prefix))
assert (enabled and env.usersite is not None) or (
@@ -1070,7 +1069,7 @@ def test_venv_has_correct_paths(tmp_venv: VirtualEnv):
assert tmp_venv.site_packages.path == Path(paths["purelib"])
-def test_env_system_packages(tmp_path: Path, poetry: "Poetry"):
+def test_env_system_packages(tmp_path: Path, poetry: Poetry):
venv_path = tmp_path / "venv"
pyvenv_cfg = venv_path / "pyvenv.cfg"
@@ -1202,9 +1201,9 @@ def test_env_finds_fallback_executables_for_generic_env(
def test_create_venv_accepts_fallback_version_w_nonzero_patchlevel(
manager: EnvManager,
- poetry: "Poetry",
- config: "Config",
- mocker: "MockerFixture",
+ poetry: Poetry,
+ config: Config,
+ mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
diff --git a/tests/utils/test_env_site.py b/tests/utils/test_env_site.py
index 6efeac9fbbb..f3fdc9bb6d3 100644
--- a/tests/utils/test_env_site.py
+++ b/tests/utils/test_env_site.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import uuid
from pathlib import Path
@@ -11,7 +13,7 @@
from pytest_mock import MockerFixture
-def test_env_site_simple(tmp_dir: str, mocker: "MockerFixture"):
+def test_env_site_simple(tmp_dir: str, mocker: MockerFixture):
# emulate permission error when creating directory
mocker.patch("pathlib.Path.mkdir", side_effect=OSError())
site_packages = SitePackages(Path("/non-existent"), fallbacks=[Path(tmp_dir)])
diff --git a/tests/utils/test_exporter.py b/tests/utils/test_exporter.py
index 53dfd0a2282..4bee492ebe4 100644
--- a/tests/utils/test_exporter.py
+++ b/tests/utils/test_exporter.py
@@ -1,15 +1,12 @@
+from __future__ import annotations
+
import sys
import textwrap
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
-from typing import Dict
from typing import Iterator
-from typing import List
-from typing import Optional
-from typing import Set
-from typing import Union
import pytest
@@ -37,12 +34,12 @@ def __init__(self) -> None:
self._locked = True
self._content_hash = self._get_content_hash()
- def locked(self, is_locked: bool = True) -> "Locker":
+ def locked(self, is_locked: bool = True) -> Locker:
self._locked = is_locked
return self
- def mock_lock_data(self, data: Dict[str, Any]):
+ def mock_lock_data(self, data: dict[str, Any]):
self._lock_data = data
def is_locked(self) -> bool:
@@ -62,8 +59,8 @@ def working_directory() -> Path:
@pytest.fixture(autouse=True)
def mock_path_cwd(
- mocker: "MockerFixture", working_directory: Path
-) -> Iterator["MockerFixture"]:
+ mocker: MockerFixture, working_directory: Path
+) -> Iterator[MockerFixture]:
yield mocker.patch("pathlib.Path.cwd", return_value=working_directory)
@@ -73,14 +70,14 @@ def locker() -> Locker:
@pytest.fixture
-def poetry(fixture_dir: "FixtureDirGetter", locker: Locker) -> "Poetry":
+def poetry(fixture_dir: FixtureDirGetter, locker: Locker) -> Poetry:
p = Factory().create_poetry(fixture_dir("sample_project"))
p._locker = locker
return p
-def set_package_requires(poetry: "Poetry", skip: Optional[Set[str]] = None) -> None:
+def set_package_requires(poetry: Poetry, skip: set[str] | None = None) -> None:
skip = skip or set()
packages = poetry.locker.locked_repository(with_dev_reqs=True).packages
package = poetry.package.with_dependency_groups([], only=True)
@@ -92,7 +89,7 @@ def set_package_requires(poetry: "Poetry", skip: Optional[Set[str]] = None) -> N
def test_exporter_can_export_requirements_txt_with_standard_packages(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -137,7 +134,7 @@ def test_exporter_can_export_requirements_txt_with_standard_packages(
def test_exporter_can_export_requirements_txt_with_standard_packages_and_markers(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -192,7 +189,7 @@ def test_exporter_can_export_requirements_txt_with_standard_packages_and_markers
assert content == expected
-def test_exporter_can_export_requirements_txt_poetry(tmp_dir: str, poetry: "Poetry"):
+def test_exporter_can_export_requirements_txt_poetry(tmp_dir: str, poetry: Poetry):
"""Regression test for #3254"""
poetry.locker.mock_lock_data(
@@ -310,9 +307,7 @@ def test_exporter_can_export_requirements_txt_poetry(tmp_dir: str, poetry: "Poet
assert dependency.marker == expected_dependency.marker
-def test_exporter_can_export_requirements_txt_pyinstaller(
- tmp_dir: str, poetry: "Poetry"
-):
+def test_exporter_can_export_requirements_txt_pyinstaller(tmp_dir: str, poetry: Poetry):
"""Regression test for #3254"""
poetry.locker.mock_lock_data(
@@ -390,7 +385,7 @@ def test_exporter_can_export_requirements_txt_pyinstaller(
def test_exporter_can_export_requirements_txt_with_nested_packages_and_markers(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -475,7 +470,7 @@ def test_exporter_can_export_requirements_txt_with_nested_packages_and_markers(
[(False, ['a==1.2.3 ; python_version < "3.8"']), (True, ["a==1.2.3", "b==4.5.6"])],
)
def test_exporter_can_export_requirements_txt_with_nested_packages_and_markers_any(
- tmp_dir: str, poetry: "Poetry", dev: bool, lines: List[str]
+ tmp_dir: str, poetry: Poetry, dev: bool, lines: list[str]
):
poetry.locker.mock_lock_data(
{
@@ -528,7 +523,7 @@ def test_exporter_can_export_requirements_txt_with_nested_packages_and_markers_a
def test_exporter_can_export_requirements_txt_with_standard_packages_and_hashes(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -575,7 +570,7 @@ def test_exporter_can_export_requirements_txt_with_standard_packages_and_hashes(
def test_exporter_can_export_requirements_txt_with_standard_packages_and_hashes_disabled( # noqa: E501
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -622,7 +617,7 @@ def test_exporter_can_export_requirements_txt_with_standard_packages_and_hashes_
def test_exporter_exports_requirements_txt_without_dev_packages_by_default(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -667,7 +662,7 @@ def test_exporter_exports_requirements_txt_without_dev_packages_by_default(
def test_exporter_exports_requirements_txt_with_dev_packages_if_opted_in(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -714,7 +709,7 @@ def test_exporter_exports_requirements_txt_with_dev_packages_if_opted_in(
def test_exporter_exports_requirements_txt_without_optional_packages(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -769,9 +764,9 @@ def test_exporter_exports_requirements_txt_without_optional_packages(
)
def test_exporter_exports_requirements_txt_with_optional_packages(
tmp_dir: str,
- poetry: "Poetry",
- extras: Optional[Union[bool, List[str]]],
- lines: List[str],
+ poetry: Poetry,
+ extras: bool | list[str] | None,
+ lines: list[str],
):
poetry.locker.mock_lock_data(
{
@@ -829,7 +824,7 @@ def test_exporter_exports_requirements_txt_with_optional_packages(
def test_exporter_can_export_requirements_txt_with_git_packages(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -871,7 +866,7 @@ def test_exporter_can_export_requirements_txt_with_git_packages(
def test_exporter_can_export_requirements_txt_with_nested_packages(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -922,7 +917,7 @@ def test_exporter_can_export_requirements_txt_with_nested_packages(
def test_exporter_can_export_requirements_txt_with_nested_packages_cyclic(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -978,7 +973,7 @@ def test_exporter_can_export_requirements_txt_with_nested_packages_cyclic(
def test_exporter_can_export_requirements_txt_with_nested_packages_and_multiple_markers(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -1064,7 +1059,7 @@ def test_exporter_can_export_requirements_txt_with_nested_packages_and_multiple_
def test_exporter_can_export_requirements_txt_with_git_packages_and_markers(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.locker.mock_lock_data(
{
@@ -1107,7 +1102,7 @@ def test_exporter_can_export_requirements_txt_with_git_packages_and_markers(
def test_exporter_can_export_requirements_txt_with_directory_packages(
- tmp_dir: str, poetry: "Poetry", working_directory: Path
+ tmp_dir: str, poetry: Poetry, working_directory: Path
):
poetry.locker.mock_lock_data(
{
@@ -1149,7 +1144,7 @@ def test_exporter_can_export_requirements_txt_with_directory_packages(
def test_exporter_can_export_requirements_txt_with_nested_directory_packages(
- tmp_dir: str, poetry: "Poetry", working_directory: Path
+ tmp_dir: str, poetry: Poetry, working_directory: Path
):
poetry.locker.mock_lock_data(
{
@@ -1217,7 +1212,7 @@ def test_exporter_can_export_requirements_txt_with_nested_directory_packages(
def test_exporter_can_export_requirements_txt_with_directory_packages_and_markers(
- tmp_dir: str, poetry: "Poetry", working_directory: Path
+ tmp_dir: str, poetry: Poetry, working_directory: Path
):
poetry.locker.mock_lock_data(
{
@@ -1261,7 +1256,7 @@ def test_exporter_can_export_requirements_txt_with_directory_packages_and_marker
def test_exporter_can_export_requirements_txt_with_file_packages(
- tmp_dir: str, poetry: "Poetry", working_directory: Path
+ tmp_dir: str, poetry: Poetry, working_directory: Path
):
poetry.locker.mock_lock_data(
{
@@ -1303,7 +1298,7 @@ def test_exporter_can_export_requirements_txt_with_file_packages(
def test_exporter_can_export_requirements_txt_with_file_packages_and_markers(
- tmp_dir: str, poetry: "Poetry", working_directory: Path
+ tmp_dir: str, poetry: Poetry, working_directory: Path
):
poetry.locker.mock_lock_data(
{
@@ -1347,7 +1342,7 @@ def test_exporter_can_export_requirements_txt_with_file_packages_and_markers(
def test_exporter_exports_requirements_txt_with_legacy_packages(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.pool.add_repository(
LegacyRepository(
@@ -1406,9 +1401,7 @@ def test_exporter_exports_requirements_txt_with_legacy_packages(
assert content == expected
-def test_exporter_exports_requirements_txt_with_url_false(
- tmp_dir: str, poetry: "Poetry"
-):
+def test_exporter_exports_requirements_txt_with_url_false(tmp_dir: str, poetry: Poetry):
poetry.pool.add_repository(
LegacyRepository(
"custom",
@@ -1467,7 +1460,7 @@ def test_exporter_exports_requirements_txt_with_url_false(
def test_exporter_exports_requirements_txt_with_legacy_packages_trusted_host(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.pool.add_repository(
LegacyRepository(
@@ -1525,7 +1518,7 @@ def test_exporter_exports_requirements_txt_with_legacy_packages_trusted_host(
],
)
def test_exporter_exports_requirements_txt_with_dev_extras(
- tmp_dir: str, poetry: "Poetry", dev: bool, expected: List[str]
+ tmp_dir: str, poetry: Poetry, dev: bool, expected: list[str]
):
poetry.locker.mock_lock_data(
{
@@ -1580,7 +1573,7 @@ def test_exporter_exports_requirements_txt_with_dev_extras(
def test_exporter_exports_requirements_txt_with_legacy_packages_and_duplicate_sources(
- tmp_dir: str, poetry: "Poetry"
+ tmp_dir: str, poetry: Poetry
):
poetry.pool.add_repository(
LegacyRepository(
@@ -1666,7 +1659,7 @@ def test_exporter_exports_requirements_txt_with_legacy_packages_and_duplicate_so
def test_exporter_exports_requirements_txt_with_legacy_packages_and_credentials(
- tmp_dir: str, poetry: "Poetry", config: "Config"
+ tmp_dir: str, poetry: Poetry, config: Config
):
poetry.config.merge(
{
@@ -1735,7 +1728,7 @@ def test_exporter_exports_requirements_txt_with_legacy_packages_and_credentials(
def test_exporter_exports_requirements_txt_to_standard_output(
- tmp_dir: str, poetry: "Poetry", capsys: "CaptureFixture"
+ tmp_dir: str, poetry: Poetry, capsys: CaptureFixture
):
poetry.locker.mock_lock_data(
{
diff --git a/tests/utils/test_extras.py b/tests/utils/test_extras.py
index 68e43aea8bf..67d1963bcc2 100644
--- a/tests/utils/test_extras.py
+++ b/tests/utils/test_extras.py
@@ -1,5 +1,4 @@
-from typing import Dict
-from typing import List
+from __future__ import annotations
import pytest
@@ -60,10 +59,10 @@
],
)
def test_get_extra_package_names(
- packages: List[Package],
- extras: Dict[str, List[str]],
- extra_names: List[str],
- expected_extra_package_names: List[str],
+ packages: list[Package],
+ extras: dict[str, list[str]],
+ extra_names: list[str],
+ expected_extra_package_names: list[str],
):
assert (
list(get_extra_package_names(packages, extras, extra_names))
diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.py
index a4781062ca7..fa452749f0b 100644
--- a/tests/utils/test_helpers.py
+++ b/tests/utils/test_helpers.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from pathlib import Path
from typing import TYPE_CHECKING
@@ -70,14 +72,14 @@ def test_parse_requires():
assert result == expected
-def test_get_cert(config: "Config"):
+def test_get_cert(config: Config):
ca_cert = "path/to/ca.pem"
config.merge({"certificates": {"foo": {"cert": ca_cert}}})
assert get_cert(config, "foo") == Path(ca_cert)
-def test_get_client_cert(config: "Config"):
+def test_get_client_cert(config: Config):
client_cert = "path/to/client.pem"
config.merge({"certificates": {"foo": {"client-cert": client_cert}}})
diff --git a/tests/utils/test_password_manager.py b/tests/utils/test_password_manager.py
index c9012077dd0..27747cfb484 100644
--- a/tests/utils/test_password_manager.py
+++ b/tests/utils/test_password_manager.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
from typing import TYPE_CHECKING
@@ -17,7 +19,7 @@
def test_set_http_password(
- config: "Config", with_simple_keyring: None, dummy_keyring: "DummyBackend"
+ config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend
):
manager = PasswordManager(config)
@@ -32,7 +34,7 @@ def test_set_http_password(
def test_get_http_auth(
- config: "Config", with_simple_keyring: None, dummy_keyring: "DummyBackend"
+ config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend
):
dummy_keyring.set_password("poetry-repository-foo", "bar", "baz")
config.auth_config_source.add_property("http-basic.foo", {"username": "bar"})
@@ -46,7 +48,7 @@ def test_get_http_auth(
def test_delete_http_password(
- config: "Config", with_simple_keyring: None, dummy_keyring: "DummyBackend"
+ config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend
):
dummy_keyring.set_password("poetry-repository-foo", "bar", "baz")
config.auth_config_source.add_property("http-basic.foo", {"username": "bar"})
@@ -60,7 +62,7 @@ def test_delete_http_password(
def test_set_pypi_token(
- config: "Config", with_simple_keyring: None, dummy_keyring: "DummyBackend"
+ config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend
):
manager = PasswordManager(config)
@@ -73,7 +75,7 @@ def test_set_pypi_token(
def test_get_pypi_token(
- config: "Config", with_simple_keyring: None, dummy_keyring: "DummyBackend"
+ config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend
):
dummy_keyring.set_password("poetry-repository-foo", "__token__", "baz")
manager = PasswordManager(config)
@@ -83,7 +85,7 @@ def test_get_pypi_token(
def test_delete_pypi_token(
- config: "Config", with_simple_keyring: None, dummy_keyring: "DummyBackend"
+ config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend
):
dummy_keyring.set_password("poetry-repository-foo", "__token__", "baz")
manager = PasswordManager(config)
@@ -95,7 +97,7 @@ def test_delete_pypi_token(
def test_set_http_password_with_unavailable_backend(
- config: "Config", with_fail_keyring: None
+ config: Config, with_fail_keyring: None
):
manager = PasswordManager(config)
@@ -108,7 +110,7 @@ def test_set_http_password_with_unavailable_backend(
def test_get_http_auth_with_unavailable_backend(
- config: "Config", with_fail_keyring: None
+ config: Config, with_fail_keyring: None
):
config.auth_config_source.add_property(
"http-basic.foo", {"username": "bar", "password": "baz"}
@@ -123,7 +125,7 @@ def test_get_http_auth_with_unavailable_backend(
def test_delete_http_password_with_unavailable_backend(
- config: "Config", with_fail_keyring: None
+ config: Config, with_fail_keyring: None
):
config.auth_config_source.add_property(
"http-basic.foo", {"username": "bar", "password": "baz"}
@@ -137,7 +139,7 @@ def test_delete_http_password_with_unavailable_backend(
def test_set_pypi_token_with_unavailable_backend(
- config: "Config", with_fail_keyring: None
+ config: Config, with_fail_keyring: None
):
manager = PasswordManager(config)
@@ -148,7 +150,7 @@ def test_set_pypi_token_with_unavailable_backend(
def test_get_pypi_token_with_unavailable_backend(
- config: "Config", with_fail_keyring: None
+ config: Config, with_fail_keyring: None
):
config.auth_config_source.add_property("pypi-token.foo", "baz")
manager = PasswordManager(config)
@@ -158,7 +160,7 @@ def test_get_pypi_token_with_unavailable_backend(
def test_delete_pypi_token_with_unavailable_backend(
- config: "Config", with_fail_keyring: None
+ config: Config, with_fail_keyring: None
):
config.auth_config_source.add_property("pypi-token.foo", "baz")
manager = PasswordManager(config)
@@ -170,7 +172,7 @@ def test_delete_pypi_token_with_unavailable_backend(
def test_keyring_raises_errors_on_keyring_errors(
- mocker: "MockerFixture", with_fail_keyring: None
+ mocker: MockerFixture, with_fail_keyring: None
):
mocker.patch("poetry.utils.password_manager.KeyRing._check")
@@ -194,7 +196,7 @@ def test_keyring_with_chainer_backend_and_not_compatible_only_should_be_unavaila
def test_get_http_auth_from_environment_variables(
- environ: None, config: "Config", with_simple_keyring: None
+ environ: None, config: Config, with_simple_keyring: None
):
os.environ["POETRY_HTTP_BASIC_FOO_USERNAME"] = "bar"
os.environ["POETRY_HTTP_BASIC_FOO_PASSWORD"] = "baz"
diff --git a/tests/utils/test_patterns.py b/tests/utils/test_patterns.py
index dc3dc964563..098a41d3ce5 100644
--- a/tests/utils/test_patterns.py
+++ b/tests/utils/test_patterns.py
@@ -1,5 +1,4 @@
-from typing import Dict
-from typing import Optional
+from __future__ import annotations
import pytest
@@ -35,7 +34,7 @@
),
],
)
-def test_wheel_file_re(filename: str, expected: Dict[str, Optional[str]]):
+def test_wheel_file_re(filename: str, expected: dict[str, str | None]):
match = patterns.wheel_file_re.match(filename)
groups = match.groupdict()
diff --git a/tests/utils/test_pip.py b/tests/utils/test_pip.py
index 31762e02d6d..c1c5c2aefc4 100644
--- a/tests/utils/test_pip.py
+++ b/tests/utils/test_pip.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import subprocess
from typing import TYPE_CHECKING
@@ -18,7 +20,7 @@
def test_pip_install_successful(
- tmp_dir: str, tmp_venv: "VirtualEnv", fixture_dir: "FixtureDirGetter"
+ tmp_dir: str, tmp_venv: VirtualEnv, fixture_dir: FixtureDirGetter
):
file_path = fixture_dir("distributions/demo-0.1.0-py2.py3-none-any.whl")
result = pip_install(file_path, tmp_venv)
@@ -27,7 +29,7 @@ def test_pip_install_successful(
def test_pip_install_link(
- tmp_dir: str, tmp_venv: "VirtualEnv", fixture_dir: "FixtureDirGetter"
+ tmp_dir: str, tmp_venv: VirtualEnv, fixture_dir: FixtureDirGetter
):
file_path = Link(
path_to_url(fixture_dir("distributions/demo-0.1.0-py2.py3-none-any.whl"))
@@ -39,9 +41,9 @@ def test_pip_install_link(
def test_pip_install_with_keyboard_interrupt(
tmp_dir: str,
- tmp_venv: "VirtualEnv",
- fixture_dir: "FixtureDirGetter",
- mocker: "MockerFixture",
+ tmp_venv: VirtualEnv,
+ fixture_dir: FixtureDirGetter,
+ mocker: MockerFixture,
):
file_path = fixture_dir("distributions/demo-0.1.0-py2.py3-none-any.whl")
mocker.patch("subprocess.run", side_effect=KeyboardInterrupt())
diff --git a/tests/utils/test_setup_reader.py b/tests/utils/test_setup_reader.py
index a0b4584f56e..7dbf2ba91ae 100644
--- a/tests/utils/test_setup_reader.py
+++ b/tests/utils/test_setup_reader.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
from typing import Callable