summaryrefslogtreecommitdiffstats
path: root/tests/python/test_cattrs_special_cases.py
blob: c5e0e9ce22c4d9d27c32ca5c25e912ceeea80012 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from typing import Optional, Union

import attrs
import hamcrest
import pytest
from cattrs.errors import ClassValidationError

from lsprotocol import converters as cv
from lsprotocol import types as lsp


def test_simple():
    """Ensure that simple LSP types are serializable."""
    data = {
        "range": {
            "start": {"line": 0, "character": 0},
            "end": {"line": 0, "character": 0},
        },
        "message": "Missing module docstring",
        "severity": 3,
        "code": "C0114:missing-module-docstring",
        "source": "my_lint",
    }
    converter = cv.get_converter()
    obj = converter.structure(data, lsp.Diagnostic)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.Diagnostic))


def test_numeric_validation():
    """Ensure that out of range numbers raise exception."""
    data = {"line": -1, "character": 0}
    converter = cv.get_converter()
    with pytest.raises((ClassValidationError, ValueError)):
        converter.structure(data, lsp.Position)


def test_forward_refs():
    """Test that forward references are handled correctly by cattrs converter."""
    data = {
        "uri": "something.py",
        "diagnostics": [
            {
                "range": {
                    "start": {"line": 0, "character": 0},
                    "end": {"line": 0, "character": 0},
                },
                "message": "Missing module docstring",
                "severity": 3,
                "code": "C0114:missing-module-docstring",
                "source": "my_lint",
            },
            {
                "range": {
                    "start": {"line": 2, "character": 6},
                    "end": {
                        "line": 2,
                        "character": 7,
                    },
                },
                "message": "Undefined variable 'x'",
                "severity": 1,
                "code": "E0602:undefined-variable",
                "source": "my_lint",
            },
            {
                "range": {
                    "start": {"line": 0, "character": 0},
                    "end": {
                        "line": 0,
                        "character": 10,
                    },
                },
                "message": "Unused import sys",
                "severity": 2,
                "code": "W0611:unused-import",
                "source": "my_lint",
            },
        ],
    }
    converter = cv.get_converter()
    obj = converter.structure(data, lsp.PublishDiagnosticsParams)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.PublishDiagnosticsParams))


@pytest.mark.parametrize(
    "data",
    [
        {},  # No properties provided
        {"documentSelector": None},
        {"documentSelector": []},
        {"documentSelector": [{"pattern": "something/**"}]},
        {"documentSelector": [{"language": "python"}]},
        {"documentSelector": [{"scheme": "file"}]},
        {"documentSelector": [{"notebook": "jupyter"}]},
        {"documentSelector": [{"language": "python"}]},
        {"documentSelector": [{"notebook": {"notebookType": "jupyter-notebook"}}]},
        {"documentSelector": [{"notebook": {"scheme": "file"}}]},
        {"documentSelector": [{"notebook": {"pattern": "something/**"}}]},
        {
            "documentSelector": [
                {"pattern": "something/**"},
                {"language": "python"},
                {"scheme": "file"},
                {"scheme": "untitled", "language": "python"},
                {"notebook": {"pattern": "something/**"}},
                {"notebook": {"scheme": "untitled"}},
                {"notebook": {"notebookType": "jupyter-notebook"}},
                {
                    "notebook": {"notebookType": "jupyter-notebook"},
                    "language": "jupyter",
                },
            ]
        },
    ],
)
def test_union_with_complex_type(data):
    """Ensure types with multiple possible resolutions are handled correctly."""
    converter = cv.get_converter()
    obj = converter.structure(data, lsp.TextDocumentRegistrationOptions)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.TextDocumentRegistrationOptions))


def test_keyword_field():
    """Ensure that fields same names as keywords are handled correctly."""
    data = {
        "from": {
            "name": "something",
            "kind": 5,
            "uri": "something.py",
            "range": {
                "start": {"line": 0, "character": 0},
                "end": {
                    "line": 0,
                    "character": 10,
                },
            },
            "selectionRange": {
                "start": {"line": 0, "character": 2},
                "end": {
                    "line": 0,
                    "character": 8,
                },
            },
            "data": {"something": "some other"},
        },
        "fromRanges": [
            {
                "start": {"line": 0, "character": 0},
                "end": {
                    "line": 0,
                    "character": 10,
                },
            },
            {
                "start": {"line": 12, "character": 0},
                "end": {
                    "line": 13,
                    "character": 0,
                },
            },
        ],
    }

    converter = cv.get_converter()
    obj = converter.structure(data, lsp.CallHierarchyIncomingCall)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.CallHierarchyIncomingCall))
    rev = converter.unstructure(obj, lsp.CallHierarchyIncomingCall)
    hamcrest.assert_that(rev, hamcrest.is_(data))


@pytest.mark.parametrize(
    "data",
    [
        {"settings": None},
        {"settings": 100000},
        {"settings": 1.23456},
        {"settings": True},
        {"settings": "something"},
        {"settings": {"something": "something"}},
        {"settings": []},
        {"settings": [None, None]},
        {"settings": [None, 1, 1.23, True]},
    ],
)
def test_LSPAny(data):
    """Ensure that broad primitive and custom type alias is handled correctly."""
    converter = cv.get_converter()
    obj = converter.structure(data, lsp.DidChangeConfigurationParams)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.DidChangeConfigurationParams))
    hamcrest.assert_that(
        converter.unstructure(obj, lsp.DidChangeConfigurationParams),
        hamcrest.is_(data),
    )


@pytest.mark.parametrize(
    "data",
    [
        {"label": "hi"},
        {"label": [0, 42]},
    ],
)
def test_ParameterInformation(data):
    converter = cv.get_converter()
    obj = converter.structure(data, lsp.ParameterInformation)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.ParameterInformation))
    hamcrest.assert_that(
        converter.unstructure(obj, lsp.ParameterInformation),
        hamcrest.is_(data),
    )


def test_completion_item():
    data = dict(label="example", documentation="This is documented")
    converter = cv.get_converter()
    obj = converter.structure(data, lsp.CompletionItem)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.CompletionItem))
    hamcrest.assert_that(
        converter.unstructure(obj, lsp.CompletionItem),
        hamcrest.is_(data),
    )


def test_notebook_change_event():
    data = {
        "notebookDocument": {
            "uri": "untitled:Untitled-1.ipynb?jupyter-notebook",
            "notebookType": "jupyter-notebook",
            "version": 0,
            "cells": [
                {
                    "kind": 2,
                    "document": "vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W0sdW50aXRsZWQ%3D",
                    "metadata": {"custom": {"metadata": {}}},
                }
            ],
            "metadata": {
                "custom": {
                    "cells": [],
                    "metadata": {
                        "orig_nbformat": 4,
                        "language_info": {"name": "python"},
                    },
                },
                "indentAmount": " ",
            },
        },
        "cellTextDocuments": [
            {
                "uri": "vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W0sdW50aXRsZWQ%3D",
                "languageId": "python",
                "version": 1,
                "text": "",
            }
        ],
    }

    converter = cv.get_converter()
    obj = converter.structure(data, lsp.DidOpenNotebookDocumentParams)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.DidOpenNotebookDocumentParams))
    hamcrest.assert_that(
        converter.unstructure(obj, lsp.DidOpenNotebookDocumentParams),
        hamcrest.is_(data),
    )


def test_notebook_sync_options():
    data = {"notebookSelector": [{"cells": [{"language": "python"}]}]}

    converter = cv.get_converter()
    obj = converter.structure(data, lsp.NotebookDocumentSyncOptions)
    hamcrest.assert_that(obj, hamcrest.instance_of(lsp.NotebookDocumentSyncOptions))
    hamcrest.assert_that(
        converter.unstructure(obj, lsp.NotebookDocumentSyncOptions),
        hamcrest.is_(data),
    )


@attrs.define
class TestPosEncoding:
    """Defines the capabilities provided by a language
    server."""

    position_encoding: Optional[Union[lsp.PositionEncodingKind, str]] = attrs.field(
        default=None
    )


@pytest.mark.parametrize("e", [None, "utf-8", "utf-16", "utf-32", "something"])
def test_position_encoding_kind(e):
    data = {"positionEncoding": e}
    converter = cv.get_converter()
    obj = converter.structure(data, TestPosEncoding)
    hamcrest.assert_that(obj, hamcrest.instance_of(TestPosEncoding))

    if e is None:
        hamcrest.assert_that(
            converter.unstructure(obj, TestPosEncoding), hamcrest.is_({})
        )
    else:
        hamcrest.assert_that(
            converter.unstructure(obj, TestPosEncoding), hamcrest.is_(data)
        )