Ejemplo n.º 1
0
def test_document_multiline_edit():
    old = [
        "def hello(a, b):\n",
        "    print a\n",
        "    print b\n"
    ]
    doc = Document('file:///uri', u''.join(old), sync_kind=TextDocumentSyncKind.INCREMENTAL)
    change = TextDocumentContentChangeEvent(
        range=Range(start=Position(line=1, character=4), end=Position(line=2, character=11)),
        range_length=0,
        text=u'print a, b')
    doc.apply_change(change)

    assert doc.lines == [
        "def hello(a, b):\n",
        "    print a, b\n"
    ]

    doc = Document('file:///uri', u''.join(old), sync_kind=TextDocumentSyncKind.INCREMENTAL)
    change = TextDocumentContentChangeEvent(
        range=Range(start=Position(line=1, character=4), end=Position(line=2, character=11)),
        text=u'print a, b')
    doc.apply_change(change)

    assert doc.lines == [
        "def hello(a, b):\n",
        "    print a, b\n"
    ]
Ejemplo n.º 2
0
def test_completion():
    uri = 'file://test_completion.py'
    content = '''
def foo(a, *, b, c=None):
    pass

foo'''
    doc = Document(uri, content)
    server.workspace.get_document = Mock(return_value=doc)
    aserver.completionFunction = aserver._completions_snippets
    completion = aserver.completions(
        server,
        types.CompletionParams(
            text_document=types.TextDocumentIdentifier(uri=uri),
            position=types.Position(line=4, character=3),
            context=types.CompletionContext(
                trigger_kind=types.CompletionTriggerKind.Invoked)))
    assert len(completion.items) == 2
    item = completion.items[0]
    assert item.insert_text is None
    assert item.label == 'foo'
    assert item.sort_text == 'aaafoo'
    assert item.insert_text_format is None
    item = completion.items[1]
    assert item.label == 'foo(a, b)'
    assert item.sort_text == 'aazfoo'
    assert item.insert_text_format == types.InsertTextFormat.Snippet
    assert item.insert_text == 'foo(${1:a}, b=${2:b})$0'
Ejemplo n.º 3
0
def test_document_empty_edit():
    doc = Document('file:///uri', u'')
    change = TextDocumentContentChangeEvent(
        range=Range(start=Position(line=0, character=0), end=Position(line=0, character=0)),
        range_length=0,
        text=u'f')
    doc.apply_change(change)
    assert doc.source == u'f'
Ejemplo n.º 4
0
def test_document_multiline_edit():
    old = ["def hello(a, b):\n", "    print a\n", "    print b\n"]
    doc = Document('file:///uri', u''.join(old))
    change = TextDocumentContentChangeEvent(
        Range(Position(1, 4), Position(2, 11)), 0, u'print a, b')
    doc.apply_change(change)

    assert doc.lines == ["def hello(a, b):\n", "    print a, b\n"]
Ejemplo n.º 5
0
def test_document_line_edit():
    doc = Document('file:///uri', u'itshelloworld')
    change = TextDocumentContentChangeEvent(
        range=Range(start=Position(line=0, character=3), end=Position(line=0, character=8)),
        range_length=0,
        text=u'goodbye')
    doc.apply_change(change)
    assert doc.source == u'itsgoodbyeworld'
Ejemplo n.º 6
0
def test_document_full_edit():
    old = ["def hello(a, b):\n", "    print a\n", "    print b\n"]
    doc = Document('file:///uri',
                   u''.join(old),
                   sync_kind=TextDocumentSyncKind.FULL)
    change = TextDocumentContentChangeEvent(
        Range(Position(1, 4), Position(2, 11)), 0, u'print a, b')
    doc.apply_change(change)

    assert doc.lines == ["print a, b"]

    doc = Document('file:///uri',
                   u''.join(old),
                   sync_kind=TextDocumentSyncKind.FULL)
    change = TextDocumentContentChangeEvent(range=None, text=u'print a, b')
    doc.apply_change(change)

    assert doc.lines == ["print a, b"]
Ejemplo n.º 7
0
    def to_document(source: str, uri: str = "file://fake_doc.xml", version: int = 0) -> Document:
        """Converts the given string into a Document.

        Args:
            - source (str): The input string to be converted to Document.
            - uri (str, optional): The uri of the document. Defaults to "file://fake_doc.xml".
            - version (int, optional): The version of the document. Defaults to 0.

        Returns:
            Document: The resulting Document.
        """
        return Document(uri, source, version)
Ejemplo n.º 8
0
    def from_source_to_xml_document(source: str, uri: str = "file://fake_doc.xml", version: int = 0) -> XmlDocument:
        """Converts the given string into a parsed XML document.

        Args:
            - source (str): The input string to be converted to XmlDocument.
            - uri (str, optional): The uri of the document. Defaults to "file://fake_doc.xml".
            - version (int, optional): The version of the document. Defaults to 0.

        Returns:
            XmlDocument: The resulting XML document.
        """
        document = Document(uri, source, version)
        return TestUtils.from_document_to_xml_document(document)
Ejemplo n.º 9
0
    def get_test_document_from_file(filename: str) -> Document:
        """Gets a Document object from the tests/files directory with the given
        filename.

        Args:
            filename (str): The filename, including the extension.

        Returns:
            Document: The Document object of the test file.
        """
        path = Path(__file__).parent.parent / "files" / filename
        uri = path.as_uri()
        return Document(uri)
Ejemplo n.º 10
0
def test_document_end_of_file_edit():
    old = ["print 'a'\n", "print 'b'\n"]
    doc = Document('file:///uri', u''.join(old))

    change = TextDocumentContentChangeEvent(
        Range(Position(2, 0), Position(2, 0)), 0, u'o')
    doc.apply_change(change)

    assert doc.lines == [
        "print 'a'\n",
        "print 'b'\n",
        "o",
    ]
 def _get_expanded_tool_document(self, tool_document: GalaxyToolXmlDocument) -> GalaxyToolXmlDocument:
     """If the given tool document uses macros, a new tool document with the expanded macros is returned,
     otherwise, the same document is returned.
     """
     if tool_document.uses_macros:
         try:
             document = tool_document.document
             expanded_tool_tree, _ = xml_macros.load_with_references(document.path)
             expanded_tool_tree = cast(etree._ElementTree, expanded_tool_tree)
             expanded_source = etree.tostring(expanded_tool_tree, encoding=str)
             expanded_document = Document(uri=document.uri, source=expanded_source, version=document.version)
             return GalaxyToolXmlDocument(expanded_document)
         except BaseException:
             return tool_document
     return tool_document
Ejemplo n.º 12
0
def test_hover():
    uri = 'file://test_hover.py'
    content = '''
def foo(a, *, b, c=None):
    """docstring"""
    pass

foo'''
    doc = Document(uri, content)
    server.workspace.get_document = Mock(return_value=doc)
    h = aserver.hover(
        server, types.TextDocumentPositionParams(doc, types.Position(5, 0)))
    assert h is not None
    assert isinstance(h.contents, types.MarkupContent)
    assert h.contents.kind == types.MarkupKind.PlainText
    assert h.contents.value == 'foo(a, *, b, c=None)\n\ndocstring'
Ejemplo n.º 13
0
def test_document_end_of_file_edit():
    old = [
        "print 'a'\n",
        "print 'b'\n"
    ]
    doc = Document('file:///uri', u''.join(old))

    change = TextDocumentContentChangeEvent(
        range=Range(start=Position(line=2, character=0), end=Position(line=2, character=0)),
        range_length=0,
        text=u'o')
    doc.apply_change(change)

    assert doc.lines == [
        "print 'a'\n",
        "print 'b'\n",
        "o",
    ]
Ejemplo n.º 14
0
def test_document_empty_edit():
    doc = Document('file:///uri', u'')
    change = TextDocumentContentChangeEvent(
        Range(Position(0, 0), Position(0, 0)), 0, u'f')
    doc.apply_change(change)
    assert doc.source == u'f'
Ejemplo n.º 15
0
def test_document_source_unicode():
    document_mem = Document(DOC_URI, u'my source')
    document_disk = Document(DOC_URI)
    assert isinstance(document_mem.source, type(document_disk.source))
Ejemplo n.º 16
0
def doc():
    return Document('uri', 'source')
Ejemplo n.º 17
0
from ...server import completions, did_close, did_open


class FakeServer():
    """We don't need real server to unit test features."""
    publish_diagnostics = None
    show_message = None
    show_message_log = None

    def __init__(self):
        self.workspace = Workspace('', None)


fake_document_uri = 'file://fake_doc.txt'
fake_document_content = 'text'
fake_document = Document(fake_document_uri, fake_document_content)

server = FakeServer()
server.publish_diagnostics = Mock()
server.show_message = Mock()
server.show_message_log = Mock()
server.workspace.get_document = Mock(return_value=fake_document)


def _reset_mocks():
    server.publish_diagnostics.reset_mock()
    server.show_message.reset_mock()
    server.show_message_log.reset_mock()


def test_completions():
Ejemplo n.º 18
0
def doc():
    return Document(DOC_URI, DOC)
Ejemplo n.º 19
0
def completion_test(feature, text: str, expected: Optional[Set[str]],
                    unexpected: Optional[Set[str]]):
    """Check to see if a feature provides the correct completion suggestions.

    **Only checking CompletionItem labels is supported**

    This function takes the given ``feature`` and calls it in the same manner as the
    real language server so that it can simulate real usage without being a full blown
    integration test.

    This requires ``suggest_triggers`` to be set and it to have a working ``suggest``
    method.

    Completions will be asked for with the cursor's position to be at the end of the
    inserted ``text`` in a blank document by default. If your test case requires
    additional context this can be included in ``text`` delimited by a ``\\f`` character.

    For example to pass text representing the following scenario (``^`` represents the
    user's cursor)::

       .. image:: filename.png
          :align: center
          :
           ^

    The ``text`` parameter should be set to
    ``.. image:: filename.png\\n   :align: center\\n\\f   :``. It's important to note that
    newlines **cannot** come after the ``\\f`` character.

    If you want to test the case where no completions should be suggested, pass ``None``
    to both the ``expected`` and ``unexpected`` parameters.

    Parameters
    ----------
    feature:
       An instance of the language service feature to test.
    text:
       The text to offer completion suggestions for.
    expected:
       The set of completion item labels you expect to see in the output.
    unexpected:
       The set of completion item labels you do *not* expect to see in the output.
    """

    if "\f" in text:
        contents, text = text.split("\f")
    else:
        contents = ""

    logger.debug("Context text:    '%s'", contents)
    logger.debug("Insertsion text: '%s'", text)
    assert "\n" not in text, "Insertion text cannot contain newlines"

    document = Document("file:///test_doc.rst", contents)
    position = Position(len(document.lines), len(text) - 1)

    results = []
    for trigger in feature.suggest_triggers:
        match = trigger.match(text)
        logger.debug("Match: %s", match)

        if match:
            results += feature.suggest(match, document, position)

    items = {item.label for item in results}

    logger.debug("Results:    %s", items)
    logger.debug("Expected:   %s", expected)
    logger.debug("Unexpected: %s", unexpected)

    if expected is None:
        assert len(items) == 0
    else:
        assert expected == items & expected
        assert set() == items & unexpected
Ejemplo n.º 20
0
def test_document_line_edit():
    doc = Document('file:///uri', u'itshelloworld')
    change = TextDocumentContentChangeEvent(
        Range(Position(0, 3), Position(0, 8)), 0, u'goodbye')
    doc.apply_change(change)
    assert doc.source == u'itsgoodbyeworld'
Ejemplo n.º 21
0
def didopen(params: DidOpenTextDocumentParams):
    uri = params.textDocument.uri
    txt[uri] = Document(uri)
    with compiler:
        compiler.compile(uri, params.textDocument.text)
Ejemplo n.º 22
0
"""

TEST_TOOL_01 = """<tool id="test" name="Test Tool 01" version="0.1.0">
    <command detect_errors="exit_code"><![CDATA[
        TODO: Fill in command template.
    ]]></command>
    <inputs>
    </inputs>
    <outputs>
    </outputs>
    <help><![CDATA[
        TODO: Fill in help.
    ]]></help>
</tool>
"""
TEST_TOOL_01_DOCUMENT = Document("file://test01.xml", TEST_TOOL_01)

TEST_TOOL_WITH_MACRO_01 = """
<tool id="test_with_macro" name="Test with macro 01" version="@WRAPPER_VERSION@">
    <macros>
        <import>macros.xml</import>
    </macros>
    <expand macro="inputs" />
</tool>"""
TEST_TOOL_WITH_MACRO_01_DOCUMENT = Document("file://test_with_macro_01.xml", TEST_TOOL_WITH_MACRO_01)

TEST_MACRO_01 = """
<macros>
    <token name="@WRAPPER_VERSION@">0.1.0</token>
    <macro name="inputs">
        <inputs/>
Ejemplo n.º 23
0
from mock import Mock
from pygls.types import (DidCloseTextDocumentParams, DidOpenTextDocumentParams,
                         TextDocumentIdentifier, TextDocumentItem)
from pygls.workspace import Document, Workspace

from ...server import completions, did_close, did_open


class FakeServer():
    """We don't need real server to unit test features."""
    def __init__(self):
        self.workspace = Workspace('', None)


fake_document_uri = 'file://fake_doc.txt'
fake_document = Document(fake_document_uri, '')

server = FakeServer()
server.publish_diagnostics = Mock()
server.show_message = Mock()
server.show_message_log = Mock()
server.workspace.get_document = Mock(return_value=fake_document)


def _reset_mocks():
    server.publish_diagnostics.reset_mock()
    server.show_message.reset_mock()
    server.show_message_log.reset_mock()


def test_completions():