From c45ab50cd6ba94c35b32baa0d5b4687f1339b20b Mon Sep 17 00:00:00 2001 From: Alex Carney Date: Mon, 26 Aug 2024 14:47:37 +0100 Subject: [PATCH] pytest-lsp: pyupgrade --py39-plus --- lib/pytest-lsp/changes/178.breaking.md | 1 + lib/pytest-lsp/pytest_lsp/checks.py | 15 ++++---- lib/pytest-lsp/pytest_lsp/client.py | 52 ++++++++++---------------- lib/pytest-lsp/pytest_lsp/plugin.py | 17 ++++----- lib/pytest-lsp/ruff_defaults.toml | 2 - 5 files changed, 35 insertions(+), 52 deletions(-) create mode 100644 lib/pytest-lsp/changes/178.breaking.md diff --git a/lib/pytest-lsp/changes/178.breaking.md b/lib/pytest-lsp/changes/178.breaking.md new file mode 100644 index 0000000..a7d42d9 --- /dev/null +++ b/lib/pytest-lsp/changes/178.breaking.md @@ -0,0 +1 @@ +Drop Python 3.8 support diff --git a/lib/pytest-lsp/pytest_lsp/checks.py b/lib/pytest-lsp/pytest_lsp/checks.py index b49cd9c..8720d8a 100644 --- a/lib/pytest-lsp/pytest_lsp/checks.py +++ b/lib/pytest-lsp/pytest_lsp/checks.py @@ -9,15 +9,14 @@ """ +from __future__ import annotations + # ruff: noqa: S101 import logging import warnings from typing import Any from typing import Callable -from typing import Dict -from typing import List from typing import Optional -from typing import Set from typing import Union from lsprotocol import types @@ -27,8 +26,8 @@ ParamsChecker = Callable[[types.ClientCapabilities, Any], None] ResultChecker = Callable[[types.ClientCapabilities, Any], None] -PARAMS_CHECKS: Dict[str, ParamsChecker] = {} -RESULT_CHECKS: Dict[str, ResultChecker] = {} +PARAMS_CHECKS: dict[str, ParamsChecker] = {} +RESULT_CHECKS: dict[str, ResultChecker] = {} class LspSpecificationWarning(UserWarning): @@ -135,7 +134,7 @@ def check_params_against_client_capabilities( def check_completion_item( item: types.CompletionItem, commit_characters_support: bool, - documentation_formats: Set[str], + documentation_formats: set[str], snippet_support: bool, ): """Ensure that the given ``CompletionItem`` complies with the given capabilities.""" @@ -155,7 +154,7 @@ def check_completion_item( @check_result_for(method=types.TEXT_DOCUMENT_COMPLETION) def completion_items( capabilities: types.ClientCapabilities, - result: Union[types.CompletionList, List[types.CompletionItem], None], + result: Union[types.CompletionList, list[types.CompletionItem], None], ): """Ensure that the completion items returned from the server are compliant with the spec and the client's declared capabilities.""" @@ -230,7 +229,7 @@ def completion_item_resolve( @check_result_for(method=types.TEXT_DOCUMENT_DOCUMENT_LINK) def document_links( - capabilities: types.ClientCapabilities, result: Optional[List[types.DocumentLink]] + capabilities: types.ClientCapabilities, result: Optional[list[types.DocumentLink]] ): """Ensure that the document links returned from the server are compliant with the Spec and the client's declared capabilities.""" diff --git a/lib/pytest-lsp/pytest_lsp/client.py b/lib/pytest-lsp/pytest_lsp/client.py index 33c6dd9..b697ed9 100644 --- a/lib/pytest-lsp/pytest_lsp/client.py +++ b/lib/pytest-lsp/pytest_lsp/client.py @@ -9,6 +9,7 @@ import traceback import typing import warnings +from importlib import resources # type: ignore[no-redef] from lsprotocol import types from lsprotocol.converters import get_converter @@ -21,18 +22,8 @@ from .checks import LspSpecificationWarning from .protocol import LanguageClientProtocol -if sys.version_info < (3, 9): - import importlib_resources as resources -else: - from importlib import resources # type: ignore[no-redef] - if typing.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 __version__ = "0.4.2" @@ -44,40 +35,40 @@ class LanguageClient(BaseLanguageClient): protocol: LanguageClientProtocol - def __init__(self, *args, configuration: Optional[Dict[str, Any]] = None, **kwargs): + def __init__(self, *args, configuration: dict[str, Any] | None = None, **kwargs): if "protocol_cls" not in kwargs: kwargs["protocol_cls"] = LanguageClientProtocol super().__init__("pytest-lsp-client", __version__, *args, **kwargs) - self.capabilities: Optional[types.ClientCapabilities] = None + self.capabilities: types.ClientCapabilities | None = None """The client's capabilities.""" - self.shown_documents: List[types.ShowDocumentParams] = [] + self.shown_documents: list[types.ShowDocumentParams] = [] """Holds any received show document requests.""" - self.messages: List[types.ShowMessageParams] = [] + self.messages: list[types.ShowMessageParams] = [] """Holds any received ``window/showMessage`` requests.""" - self.log_messages: List[types.LogMessageParams] = [] + self.log_messages: list[types.LogMessageParams] = [] """Holds any received ``window/logMessage`` requests.""" - self.diagnostics: Dict[str, List[types.Diagnostic]] = {} + self.diagnostics: dict[str, list[types.Diagnostic]] = {} """Holds any recieved diagnostics.""" - self.progress_reports: Dict[ - types.ProgressToken, List[types.ProgressParams] + self.progress_reports: dict[ + types.ProgressToken, list[types.ProgressParams] ] = {} """Holds any received progress updates.""" - self.error: Optional[Exception] = None + self.error: Exception | None = None """Indicates if the client encountered an error.""" config = (configuration or {"": {}}).copy() if "" not in config: config[""] = {} - self._configuration: Dict[str, Dict[str, Any]] = config + self._configuration: dict[str, dict[str, Any]] = config """Holds ``workspace/configuration`` values.""" self._setup_log_index = 0 @@ -86,7 +77,7 @@ def __init__(self, *args, configuration: Optional[Dict[str, Any]] = None, **kwar self._last_log_index = 0 """Used to keep track of which log messages correspond with which test case.""" - self._stderr_forwarder: Optional[asyncio.Task] = None + self._stderr_forwarder: asyncio.Task | None = None """A task that forwards the server's stderr to the test process.""" async def start_io(self, cmd: str, *args, **kwargs): @@ -116,7 +107,7 @@ async def server_exit(self, server: asyncio.subprocess.Process): ) def report_server_error( - self, error: Exception, source: Union[PyglsError, JsonRpcException] + self, error: Exception, source: PyglsError | JsonRpcException ): """Called when the server does something unexpected, e.g. sending malformed JSON.""" @@ -132,8 +123,8 @@ def report_server_error( self._stop_event.set() def get_configuration( - self, *, section: Optional[str] = None, scope_uri: Optional[str] = None - ) -> Optional[Any]: + self, *, section: str | None = None, scope_uri: str | None = None + ) -> Any | None: """Get a configuration value. Parameters @@ -179,8 +170,8 @@ def set_configuration( self, item: Any, *, - section: Optional[str] = None, - scope_uri: Optional[str] = None, + section: str | None = None, + scope_uri: str | None = None, ): """Set a configuration value. @@ -287,10 +278,7 @@ def cancel_all_tasks(message: str): """Called to cancel all awaited tasks.""" for task in asyncio.all_tasks(): - if sys.version_info < (3, 9): - task.cancel() - else: - task.cancel(message) + task.cancel(message) def make_test_lsp_client() -> LanguageClient: @@ -342,7 +330,7 @@ def progress(client: LanguageClient, params: types.ProgressParams): return if (kind := params.value.get("kind", None)) == "begin": - type_: Type[Any] = types.WorkDoneProgressBegin + type_: type[Any] = types.WorkDoneProgressBegin elif kind == "report": type_ = types.WorkDoneProgressReport elif kind == "end": @@ -405,7 +393,7 @@ def client_capabilities(client_spec: str) -> types.ClientCapabilities: The requested client capabilities """ - candidates: Dict[str, pathlib.Path] = {} + candidates: dict[str, pathlib.Path] = {} client_spec = client_spec.replace("-", "_") target_version = "latest" diff --git a/lib/pytest-lsp/pytest_lsp/plugin.py b/lib/pytest-lsp/pytest_lsp/plugin.py index 76ac202..49a73d1 100644 --- a/lib/pytest-lsp/pytest_lsp/plugin.py +++ b/lib/pytest-lsp/pytest_lsp/plugin.py @@ -17,9 +17,6 @@ if typing.TYPE_CHECKING: from typing import Any from typing import Callable - from typing import Dict - from typing import List - from typing import Optional logger = logging.getLogger("client") @@ -29,7 +26,7 @@ class ClientServerConfig: """Configuration for a Client-Server connection.""" - server_command: List[str] + server_command: list[str] """The command to use to start the language server.""" client_factory: Callable[[], JsonRPCClient] = attrs.field( @@ -37,10 +34,10 @@ class ClientServerConfig: ) """Factory function to use when constructing the test client instance.""" - server_env: Optional[Dict[str, str]] = attrs.field(default=None) + server_env: dict[str, str] | None = attrs.field(default=None) """Environment variables to set when starting the server.""" - def _get_devtools_command(self, server: str) -> List[str]: + def _get_devtools_command(self, server: str) -> list[str]: """Get the lsp-devtools command required to connect to the given ``server``""" if ":" in server: @@ -55,7 +52,7 @@ def _get_devtools_command(self, server: str) -> List[str]: return ["lsp-devtools", "agent", "--host", host, "--port", port, "--"] - def get_server_command(self, devtools: Optional[str] = None) -> List[str]: + def get_server_command(self, devtools: str | None = None) -> list[str]: """Get the command to start the server with.""" server_command = [] if devtools is not None: @@ -65,7 +62,7 @@ def get_server_command(self, devtools: Optional[str] = None) -> List[str]: return server_command - async def start(self, devtools: Optional[str] = None) -> JsonRPCClient: + async def start(self, devtools: str | None = None) -> JsonRPCClient: """Return the client instance to use for the test. Parameters @@ -102,7 +99,7 @@ def pytest_addoption(parser): def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo): """Add any captured log messages to the report.""" - client: Optional[LanguageClient] = None + client: LanguageClient | None = None if not hasattr(item, "funcargs"): return @@ -162,7 +159,7 @@ def get_fixture_arguments( dict The set of arguments to pass to the user's fixture function """ - kwargs: Dict[str, Any] = {} + kwargs: dict[str, Any] = {} required_parameters = set(inspect.signature(fn).parameters.keys()) # Inject the 'request' fixture if requested diff --git a/lib/pytest-lsp/ruff_defaults.toml b/lib/pytest-lsp/ruff_defaults.toml index 9b62f5a..301a10e 100644 --- a/lib/pytest-lsp/ruff_defaults.toml +++ b/lib/pytest-lsp/ruff_defaults.toml @@ -100,7 +100,6 @@ select = [ "E742", "E743", "E902", - "E999", "EM101", "EM102", "EM103", @@ -244,7 +243,6 @@ select = [ "PLR0133", "PLR0206", "PLR0402", - "PLR1701", "PLR1711", "PLR1714", "PLR1722",