Skip to content

Commit

Permalink
refactor: wip end-to-end tests
Browse files Browse the repository at this point in the history
  • Loading branch information
alcarney committed Apr 4, 2024
1 parent a3f868d commit 686db18
Show file tree
Hide file tree
Showing 16 changed files with 146 additions and 96 deletions.
52 changes: 27 additions & 25 deletions examples/servers/code_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,26 @@
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################
import logging
import re
from pygls.server import LanguageServer
from lsprotocol.types import (
TEXT_DOCUMENT_CODE_ACTION,
CodeAction,
CodeActionKind,
CodeActionOptions,
CodeActionParams,
Position,
Range,
TextEdit,
WorkspaceEdit,
)

from lsprotocol import types

from pygls import IS_WASM
from pygls.lsp.server import LanguageServer

ADDITION = re.compile(r"^\s*(\d+)\s*\+\s*(\d+)\s*=(?=\s*$)")
server = LanguageServer("code-action-server", "v0.1")
server = LanguageServer("code-action-server", "v1")


@server.feature(
TEXT_DOCUMENT_CODE_ACTION,
CodeActionOptions(code_action_kinds=[CodeActionKind.QuickFix]),
types.TEXT_DOCUMENT_CODE_ACTION,
types.CodeActionOptions(code_action_kinds=[types.CodeActionKind.QuickFix]),
)
def code_actions(params: CodeActionParams):
def code_actions(params: types.CodeActionParams):
items = []
document_uri = params.text_document.uri
document = server.workspace.get_document(document_uri)
document = server.workspace.get_text_document(document_uri)

start_line = params.range.start.line
end_line = params.range.end.line
Expand All @@ -49,26 +42,35 @@ def code_actions(params: CodeActionParams):
for idx, line in enumerate(lines):
match = ADDITION.match(line)
if match is not None:
range_ = Range(
start=Position(line=start_line + idx, character=0),
end=Position(line=start_line + idx, character=len(line) - 1),
range_ = types.Range(
start=types.Position(line=start_line + idx, character=0),
end=types.Position(line=start_line + idx, character=len(line) - 1),
)

left = int(match.group(1))
right = int(match.group(2))
answer = left + right

text_edit = TextEdit(range=range_, new_text=f"{line.strip()} {answer}!")
text_edit = types.TextEdit(
range=range_, new_text=f"{line.strip()} {answer}!"
)

action = CodeAction(
action = types.CodeAction(
title=f"Evaluate '{match.group(0)}'",
kind=CodeActionKind.QuickFix,
edit=WorkspaceEdit(changes={document_uri: [text_edit]}),
kind=types.CodeActionKind.QuickFix,
edit=types.WorkspaceEdit(changes={document_uri: [text_edit]}),
)
items.append(action)

return items


if __name__ == "__main__":
server.start_io()
logging.basicConfig(level=logging.INFO, format="[%(levelname)s]: %(message)s")

if IS_WASM:
server.start_io()
else:
import asyncio

asyncio.run(server.start_io())
49 changes: 35 additions & 14 deletions examples/servers/code_lens.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
import logging
import re

import attrs
from lsprotocol import types

from pygls.server import LanguageServer
from pygls import IS_WASM
from pygls.lsp.server import LanguageServer

ADDITION = re.compile(r"^\s*(\d+)\s*\+\s*(\d+)\s*=(?=\s*$)")
server = LanguageServer("code-lens-server", "v1")
Expand Down Expand Up @@ -74,7 +76,7 @@ def code_lens_resolve(ls: LanguageServer, item: types.CodeLens):
right = item.data["right"]
uri = item.data["uri"]

args = dict(
args = EvaluateSumArguments(
uri=uri,
left=left,
right=right,
Expand All @@ -84,40 +86,59 @@ def code_lens_resolve(ls: LanguageServer, item: types.CodeLens):
item.command = types.Command(
title=f"Evaluate {left} + {right}",
command="codeLens.evaluateSum",
arguments=[args],
arguments=[ls.converter.unstructure(args)],
)
return item


@attrs.define
class EvaluateSumArguments:
"""Represents the arguments to be passed to ``codeLens.evaluateSum``"""

uri: str
line: int
left: int
right: int


@server.command("codeLens.evaluateSum")
def evaluate_sum(ls: LanguageServer, args):
logging.info("arguments: %s", args)
def evaluate_sum(ls: LanguageServer, arguments: EvaluateSumArguments):
logging.info("arguments: %s", arguments)

arguments = args[0]
document = ls.workspace.get_text_document(arguments["uri"])
line = document.lines[arguments["line"]]
document = ls.workspace.get_text_document(arguments.uri)
line = document.lines[arguments.line]

# Compute the edit that will update the document with the result.
answer = arguments["left"] + arguments["right"]
answer = arguments.left + arguments.right
edit = types.TextDocumentEdit(
text_document=types.OptionalVersionedTextDocumentIdentifier(
uri=arguments["uri"], version=document.version
uri=arguments.uri, version=document.version
),
edits=[
types.TextEdit(
new_text=f"{line.strip()} {answer}\n",
range=types.Range(
start=types.Position(line=arguments["line"], character=0),
end=types.Position(line=arguments["line"] + 1, character=0),
start=types.Position(line=arguments.line, character=0),
end=types.Position(line=arguments.line + 1, character=0),
),
)
],
)

# Apply the edit.
ls.apply_edit(types.WorkspaceEdit(document_changes=[edit]))
ls.workspace_apply_edit(
types.ApplyWorkspaceEditParams(
edit=types.WorkspaceEdit(document_changes=[edit]),
)
)


if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(message)s")
server.start_io()

if IS_WASM:
server.start_io()
else:
import asyncio

asyncio.run(server.start_io())
11 changes: 9 additions & 2 deletions examples/servers/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

from lsprotocol import types

from pygls.server import LanguageServer
from pygls import IS_WASM
from pygls.lsp.server import LanguageServer

COLOR = re.compile(r"""\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})(?!\w)""")
server = LanguageServer("color-server", "v1")
Expand Down Expand Up @@ -82,4 +83,10 @@ def color_presentation(params: types.ColorPresentationParams):

if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(message)s")
server.start_io()

if IS_WASM:
server.start_io()
else:
import asyncio

asyncio.run(server.start_io())
16 changes: 14 additions & 2 deletions examples/servers/goto.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

from lsprotocol import types

from pygls.server import LanguageServer
from pygls import IS_WASM
from pygls.lsp.server import LanguageServer
from pygls.workspace import TextDocument

ARGUMENT = re.compile(r"(?P<name>\w+): (?P<type>\w+)")
Expand Down Expand Up @@ -111,6 +112,11 @@ def goto_definition(ls: GotoLanguageServer, params: types.DefinitionParams):
if index is None:
return

try:
line = doc.lines[params.position.line]
except IndexError:
line = ""

word = doc.word_at_position(params.position)

# Is word a type?
Expand Down Expand Up @@ -191,4 +197,10 @@ def find_references(ls: GotoLanguageServer, params: types.ReferenceParams):

if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(message)s")
server.start_io()

if IS_WASM:
server.start_io()
else:
import asyncio

asyncio.run(server.start_io())
10 changes: 8 additions & 2 deletions examples/servers/hover.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

from lsprotocol import types

from pygls.server import LanguageServer
from pygls import IS_WASM
from pygls.lsp.server import LanguageServer

DATE_FORMATS = [
"%H:%M:%S",
Expand Down Expand Up @@ -75,4 +76,9 @@ def hover(params: types.HoverParams):
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(message)s")

server.start_io()
if IS_WASM:
server.start_io()
else:
import asyncio

asyncio.run(server.start_io())
12 changes: 10 additions & 2 deletions examples/servers/inlay_hints.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################
import logging
import re
from typing import Optional

from lsprotocol import types

from pygls.server import LanguageServer
from pygls import IS_WASM
from pygls.lsp.server import LanguageServer

NUMBER = re.compile(r"\d+")
COMMENT = re.compile(r"^#$")
Expand Down Expand Up @@ -113,4 +115,10 @@ def inlay_hint_resolve(hint: types.InlayHint):


if __name__ == "__main__":
server.start_io()
logging.basicConfig(level=logging.INFO, format="%(message)s")
if IS_WASM:
server.start_io()
else:
import asyncio

asyncio.run(server.start_io())
6 changes: 3 additions & 3 deletions tests/e2e/test_code_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
if typing.TYPE_CHECKING:
from typing import Tuple

from pygls.lsp.client import BaseLanguageClient
from pygls.lsp.client import LanguageClient


@pytest_asyncio.fixture()
Expand All @@ -34,7 +34,7 @@ async def code_actions(get_client_for):


async def test_code_actions(
code_actions: Tuple[BaseLanguageClient, types.InitializeResult], uri_for
code_actions: Tuple[LanguageClient, types.InitializeResult], uri_for
):
"""Ensure that the example code action server is working as expected."""
client, initialize_result = code_actions
Expand All @@ -45,7 +45,7 @@ async def test_code_actions(
test_uri = uri_for("sums.txt")
assert test_uri is not None

response = await client.text_document_code_action_async(
response = await client.text_document_code_action(
types.CodeActionParams(
text_document=types.TextDocumentIdentifier(uri=test_uri),
range=types.Range(
Expand Down
20 changes: 8 additions & 12 deletions tests/e2e/test_code_lens.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
if typing.TYPE_CHECKING:
from typing import Tuple

from pygls.lsp.client import BaseLanguageClient
from pygls.lsp.client import LanguageClient


@pytest_asyncio.fixture(scope="module")
Expand All @@ -36,7 +36,7 @@ async def code_lens(get_client_for):

@pytest.mark.asyncio(scope="module")
async def test_code_lens(
code_lens: Tuple[BaseLanguageClient, types.InitializeResult], uri_for
code_lens: Tuple[LanguageClient, types.InitializeResult], uri_for
):
"""Ensure that the example code lens server is working as expected."""
client, initialize_result = code_lens
Expand All @@ -45,7 +45,7 @@ async def test_code_lens(
assert code_lens_options.resolve_provider is True

test_uri = uri_for("sums.txt")
response = await client.text_document_code_lens_async(
response = await client.text_document_code_lens(
types.CodeLensParams(
text_document=types.TextDocumentIdentifier(uri=test_uri),
)
Expand Down Expand Up @@ -77,15 +77,13 @@ async def test_code_lens(

@pytest.mark.asyncio(scope="module")
async def test_code_lens_resolve(
code_lens: Tuple[BaseLanguageClient, types.InitializeResult], uri_for
code_lens: Tuple[LanguageClient, types.InitializeResult], uri_for
):
"""Ensure that the example code lens server can resolve a code lens correctly."""

client, _ = code_lens

test_uri = uri_for("sums.txt")
assert test_uri is not None

lens = types.CodeLens(
range=types.Range(
start=types.Position(line=0, character=0),
Expand All @@ -94,7 +92,7 @@ async def test_code_lens_resolve(
data=dict(left=1, right=1, uri=test_uri),
)

result = await client.code_lens_resolve_async(lens)
result = await client.code_lens_resolve(lens)

# The existing fields should not be modified.
assert result.range == lens.range
Expand All @@ -110,7 +108,7 @@ async def test_code_lens_resolve(

@pytest.mark.asyncio(scope="module")
async def test_evaluate_sum(
code_lens: Tuple[BaseLanguageClient, types.InitializeResult], uri_for
code_lens: Tuple[LanguageClient, types.InitializeResult], uri_for
):
"""Ensure that the example code lens server can execute the ``evaluateSum`` command
correctly."""
Expand All @@ -127,9 +125,7 @@ def on_edit(params: types.ApplyWorkspaceEditParams):
assert provider.commands == ["codeLens.evaluateSum"]

test_uri = uri_for("sums.txt")
assert test_uri is not None

await client.workspace_execute_command_async(
await client.workspace_execute_command(
types.ExecuteCommandParams(
command="codeLens.evaluateSum",
arguments=[dict(uri=test_uri, left=1, right=1, line=0)],
Expand All @@ -144,7 +140,7 @@ def on_edit(params: types.ApplyWorkspaceEditParams):
),
edits=[
types.TextEdit(
new_text="1 + 1 = 2\n",
new_text=f"1 + 1 = 2\n",
range=types.Range(
start=types.Position(line=0, character=0),
end=types.Position(line=1, character=0),
Expand Down
Loading

0 comments on commit 686db18

Please sign in to comment.