Skip to content

Commit

Permalink
pytest-lsp: pyupgrade --py39-plus
Browse files Browse the repository at this point in the history
  • Loading branch information
alcarney committed Aug 26, 2024
1 parent bf97e6a commit c45ab50
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 52 deletions.
1 change: 1 addition & 0 deletions lib/pytest-lsp/changes/178.breaking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Drop Python 3.8 support
15 changes: 7 additions & 8 deletions lib/pytest-lsp/pytest_lsp/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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."""
Expand All @@ -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."""
Expand Down Expand Up @@ -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."""
Expand Down
52 changes: 20 additions & 32 deletions lib/pytest-lsp/pytest_lsp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand All @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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."""
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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"
Expand Down
17 changes: 7 additions & 10 deletions lib/pytest-lsp/pytest_lsp/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -29,18 +26,18 @@
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(
default=make_test_lsp_client,
)
"""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:
Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 0 additions & 2 deletions lib/pytest-lsp/ruff_defaults.toml
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ select = [
"E742",
"E743",
"E902",
"E999",
"EM101",
"EM102",
"EM103",
Expand Down Expand Up @@ -244,7 +243,6 @@ select = [
"PLR0133",
"PLR0206",
"PLR0402",
"PLR1701",
"PLR1711",
"PLR1714",
"PLR1722",
Expand Down

0 comments on commit c45ab50

Please sign in to comment.