File: stap_language_server_tester.py

package info (click to toggle)
systemtap 5.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,556 kB
  • sloc: cpp: 81,117; ansic: 54,933; xml: 49,795; exp: 43,595; sh: 11,526; python: 5,003; perl: 2,252; tcl: 1,312; makefile: 1,006; javascript: 149; lisp: 105; awk: 101; asm: 91; java: 70; sed: 16
file content (561 lines) | stat: -rw-r--r-- 21,279 bytes parent folder | download | duplicates (2)
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# Language server tests
# Copyright (C) 2022 Red Hat Inc.
#
# This file is part of systemtap, and is free software.  You can
# redistribute it and/or modify it under the terms of the GNU General
# Public License (GPL); either version 2, or (at your option) any
# later version.
from jsonrpc import ReadWriter, JSONRPC2Connection
import sys
import os
import argparse
import unittest
import subprocess
try:
    from unittest import mock
except ImportError:
    import mock
from typing import Union

class Method():
    # General
    EXIT = 'exit'
    INITIALIZE = 'initialize'
    INITIALIZED = 'initialized'
    SHUTDOWN = 'shutdown'
    TEXT_DOCUMENT_DID_CHANGE = 'textDocument/didChange'
    TEXT_DOCUMENT_DID_CLOSE = 'textDocument/didClose'
    TEXT_DOCUMENT_DID_OPEN = 'textDocument/didOpen'
    TEXT_DOCUMENT_DID_SAVE = 'textDocument/didSave'
    # Language Features
    COMPLETION = 'textDocument/completion'


class MockClient():
    def __init__(self):
        self.server_conn = None
        verbose = CMD_ARGS.verbose

        args = [CMD_ARGS.stap_path, '--language-server']
        if verbose > 0:
            args.extend(['-vvv'])
        server = subprocess.Popen(
            args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=False)
        self.server_conn = JSONRPC2Connection(
            ReadWriter(reader=server.stdout, writer=server.stdin))

        # Setup and open a doccument

        _ = self.server_conn.send_request(
            method=Method.INITIALIZE,
            params=dict(
                rootUri=f'file://{os.getcwd()}',
                capabilities=dict(),
                rootPath=os.getcwd(),
                clientInfo=dict(
                    name='test-language-server-client',
                    processId=os.getpid(),
                    trace='off'
                )
            )
        )

        self.server_conn.send_notification(Method.INITIALIZED, dict())

        self.text_document = dict(
            uri='file://fake_doc.txt',
            languageId='systemtap',
            version=1,
            text=''
        )

        self.server_conn.send_notification(
            method=Method.TEXT_DOCUMENT_DID_OPEN,
            params=dict(textDocument=self.text_document)
        )

    def __del__(self):
        # Close and showdown

        self.server_conn.send_notification(
            method=Method.TEXT_DOCUMENT_DID_CLOSE,
            params=dict(textDocument=dict(uri=self.text_document['uri']))
        )

        self.server_conn.send_notification(Method.SHUTDOWN, dict())

        self.server_conn.send_notification(Method.EXIT, dict())

    def completion_request_full(self, code_snippet, position=None):
        # If position is not provided, assume we're at the snippet end
        if not position:
            lines = code_snippet.split("\n")
            position = dict(line=len(lines)-1, character=len(lines[-1]))

        self.server_conn.send_notification(
            method=Method.TEXT_DOCUMENT_DID_CHANGE,
            params=dict(
                textDocument=dict(
                    uri=self.text_document['uri'],
                    version=1
                ),
                contentChanges=[dict(
                    text=code_snippet,
                )]
            )
        )

        return self.server_conn.send_request(
            method=Method.COMPLETION,
            params=dict(
                textDocument=dict(uri=self.text_document['uri']),
                position=position
            )
        )
    
    def completion_request_inc(self, changes, position):
        # The first change must be Full, and the remainder can be either full or incremental
        assert('range' not in changes[0])

        for v, c in enumerate(changes):
            self.server_conn.send_notification(
                method=Method.TEXT_DOCUMENT_DID_CHANGE,
                params=dict(
                    textDocument=dict(
                        uri=self.text_document['uri'],
                        version=v+1
                    ),
                    contentChanges=[c if isinstance(c, dict) else dict(text=c) ]
                )
            )

        # The insertion position should be specified when testing incremental changes
        assert(position is not None)

        return self.server_conn.send_request(
            method=Method.COMPLETION,
            params=dict(
                textDocument=dict(uri=self.text_document['uri']),
                position=position
            )
        )

class ServerCompletionTests(unittest.TestCase):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.client = MockClient() # Each testcase gets its own mockclient

    def labels_match(self, change: Union[str, list], expected, position=None, exactMatch=True, type=None, sync_kind = "full"):
        comp_func = MockClient.completion_request_inc if sync_kind != "full" else MockClient.completion_request_full

        completion_list = comp_func(self.client,
            change, position).get("result", dict())

        completion_items = completion_list.get("items", [])

        # Get the labels (the default insertion text) of type detail (if a type is provided, else everything)
        actual = [ci["label"]
                  for ci in completion_items if not type or ci["detail"] == type]

        # Expected is a subset of actual
        subset_match = all(e in actual for e in expected)
        # We may be ok with just having a subset match, or we might need an exact match
        length_match = not exactMatch or len(actual) == len(expected)

        self.assertTrue(subset_match and length_match,
                        f'\nCompleting "{change}"\nGot: {actual}\nExpected{"" if exactMatch else " Superset Of " }: {expected}')

    def test_basic(self):
        # General completions for an unknown context
        self.labels_match('pr', ['probe', 'private'])
        self.labels_match('func', ['function'])
        self.labels_match('g', ['global'])
        # the private prefix just skips private and completes like normal
        self.labels_match('private pro', ['probe'])
        # Some text/whitespace before the completion doesn't change anything
        self.labels_match('\t\n\n       p', ['probe', 'private'])
        self.labels_match(
            '%%edit foobar\t    \n\n  function foo ()\n{}\n     globa', ['global'])

    def test_probe_comps(self):
        self.labels_match('probe', [])
        # Uses match nodes correctly
        self.labels_match('probe one', ['oneshot'])
        self.labels_match('probe proces', ['process', 'process(', 'process("'])
        # Completing a second token
        self.labels_match('probe process', [
                          'process', 'process(', 'process("'])
        self.labels_match('probe process(12345678).en', ['end', 'end('])
        # Just look for a subset of expected in actual
        self.labels_match('probe process.', ['begin'], exactMatch=False)
        # Doesn't match anything
        self.labels_match('probe twosh', [])

    def test_string(self):
        file_path = os.getenv("TEST_C_FILE")

        process_prefix = 'probe process("'
        # Absolute path completion
        self.labels_match(process_prefix + '/', ['/root'], exactMatch=False)
        self.labels_match(process_prefix + '/li', ['/lib', '/lib64'])
        # Relative path completion
        self.labels_match(process_prefix + 'foo/', ['bar'])
        self.labels_match(process_prefix + 'foo/bar/', ['baz', 'baz.c'])

        # Check the text to be inserted as well, not just the label (textEdit has the same content as insertText so it's covered by this test as well)
        insert_text_test_code = process_prefix + 'foo/ba'
        actual = [(ci["label"], 'foo/ba'+ci["insertText"]) for ci in self.client.completion_request_full(
            insert_text_test_code).get("result", dict(items=[]))["items"]]
        expected = [('bar', 'foo/bar')] # = (label, prefix + insertion text)
        self.assertTrue(all(e in actual for e in expected) and len(actual) == len(expected),
            f'\nCompleting "{insert_text_test_code}"\nGot: {actual}\nExpected: {expected}')
        # TODO: Test with globs once they're supported

        # Test function/statement completion using absolute path
        self.labels_match(f'probe process("{os.getcwd().replace("build", "systemtap")}/systemtap.language_server/foo/bar/baz").function("s',
                          [f'"spam@{file_path}:1"',
                           f'"space@{file_path}:5"'])

    def test_body(self):
        prefix = "probe oneshot, foo, bar, baz { \n"
        # Body completion does not determine the structure, it will just return the available key/atwords/macros/functions
        # first line testing
        self.labels_match(prefix + 'fo', ['for', 'foreach'], type="keyword")
        self.labels_match(
            prefix + '@pr', ['probewrite', 'prometheus_dump_array1'], exactMatch=False)
        self.labels_match(
            prefix + 'ti', ['tid', 'timer_pending'], type="function")

        # Complex line testing
        line = "\t\tif ( cpu() == 0 && getti<CURSOR> > 1140498000)"
        pos = dict(line=1, character=line.find("<CURSOR>"))
        self.labels_match(prefix + line,
                          ['gettimeofday_ms', 'gettimeofday_ns', 'gettimeofday_s', 'gettimeofday_us'], position=pos)

        line = "foreach ([a,b] in foo+ lim"
        self.labels_match(prefix + line, ['limit'])

        # multiline testing
        lines = """
        function foo (a, b, c)
        {
            if (a < 1) return 0
            else if (b < 2) return 1
            else return modu
        """
        self.labels_match(lines, ['module_name', 'module_size'])

    def test_multiple_contexts(self):
        lines = """
        global baz = 42
        
        probe syscallgroup.io = syscall.open,
               syscall.read { groupname = "io" }
        function f(x) { printf("%s\n", x) }
        probe    end
        {
            f("hello world");
        foreach (eg+ in groups)
        @coun
        """
        self.labels_match(lines, ['count'])

    def test_no_completions(self):
        # Global defintions, function signatures and embedded C have no completions
        # TODO: Complete C
        self.labels_match("global x = ", [])
        self.labels_match("function foo (a, ", [])
        self.labels_match("probe", [])
        self.labels_match("function foo () %{ struc ", [])

    def test_local_definitions(self):
        code = """
        global afoo = 42
        
         function abar(x) { printf("%s", x) }
        probe    end
        {
            f("hello world");
        foreach (eg+ in groups)
        a<CURSOR>
        }
            global baz = -1

            global abaz = "hello"
        """
        lines = code.split('\n')
        cursor_line = [idx for idx, l in enumerate(lines) if '<CURSOR>' in l][0]
        pos = dict(line=cursor_line, character=lines[cursor_line].find("<CURSOR>"))
        self.labels_match(code, ['afoo', 'abar', 'abaz'], pos, False)

    def test_target_vars(self):
        code = 'function vars() {}\nprobe kernel.function("vfs_read") { $'
        self.labels_match(code, ['$file','$buf','$count','$pos', '$$vars', '$$locals', "$$parms"])

    def test_incremental_changes(self):
        def make_position(ln, chr):
            return dict(line=ln, character=chr)
        def make_change(text, range_start, range_end = None):
            if range_end is None: range_end = range_start
            return dict(
                text = text,
                range = dict(start = range_start, end = range_end)
            )

        # The first change is a full, and the remainder are incremental
        self.labels_match( [ 'pr', make_change('o', make_position(0,2)) ] , ['probe'], make_position(0, 3), True, None, "incremental")

        # Prepend a new line and then complete the new line under it (between 2 lines)
        """
        global bar = 10
        function f() { ba<CURSOR>
        probe oneshot {}
        """
        self.labels_match(
            [ 'probe oneshot {}',
              make_change('global bar = 10\n', make_position(0,0)),
              make_change('function f() { ba\n', make_position(1,0))
            ],
            ['bar'], make_position(1, 16), False, None, "incremental")

        # Append a new line and then complete the new line before it (between 2 lines)
        """
        probe oneshot {}
        function f() { ba<CURSOR>
        global bar = 10
        """
        self.labels_match(
            [ 'probe oneshot {}',
              make_change('\nglobal bar = 10', make_position(1,0)),
              make_change('function f() { ba\n', make_position(1,0))
            ],
            ['backtrace', 'bdevname', 'big_endian2', 'big_endian4', 'big_endian8',
            'bio_op', 'bio_rw_num', 'bio_rw_str', 'bytes_to_string', 'break'],
             make_position(1, 16), True, None, "incremental") # Don't match bar since its now inside the function body so its not a global

        # Modify the first and last lines and complete between them
        """
        global bar

        function f() { ba<CURSOR>}
        global baz
        """
        self.labels_match(
            [ 'global ham\nfunction f() { ba}\nglobal spam = 42',
              make_change('bar\n', make_position(0, 7), make_position(0, 10)), # replace ham with bar\n
              make_change('baz', make_position(3, 7), make_position(3, 11)),   # replace spam with baz
            ],
            ['bar', 'baz'], make_position(2, 16), False, None, "incremental")

        # Modify the first and last characters and complete between
        """
        global bar
        function f() { ba<CURSOR> }
        global baz
        """
        self.labels_match(
            [ 'flobal bar\nfunction f() { ba }\nglobal bam',
              make_change('g', make_position(0, 0), make_position(0, 1)), # replace f with g
              make_change('z', make_position(2, 9), make_position(2, 10)),   # replace m with z
            ],
            ['bar', 'baz'], make_position(1, 16), False, None, "incremental")
        
        # Remove lines and replace with new lines
        """
        probe one<CURSOR>
        """
        self.labels_match(
            [ 'global bar\nfunction foo() { return 10 }\nglobal baz',
              make_change('', make_position(0, 0), make_position(3, 11)), # remove first 3 lines
              make_change('probe one', make_position(0, 0)),   # insert into start of doc
            ],
            ['oneshot'], make_position(0, 9), False, None, "incremental")

class ServerIntegrationTests(unittest.TestCase):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.verbose = CMD_ARGS.verbose
        self.server_conn = None
        self.maxDiff = None # When asserting, show the full diff of actual and expected

    def _test_request(self, request_method: Method, request_params: dict, expected_result: dict):
        response = self.server_conn.send_request(
            request_method, request_params)
        self.assertDictEqual(response.get("result", {}), expected_result)

    def _send_notification(self, notification_method: Method, notification_params: dict = dict()):
        self.server_conn.send_notification(
            notification_method, notification_params)

    def test_basic(self):
        args = [CMD_ARGS.stap_path, '--language-server']
        if self.verbose > 0:
            args.extend(['-'+'v'*self.verbose])
        server = subprocess.Popen(
            args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=False)
        self.server_conn = JSONRPC2Connection(
            ReadWriter(reader=server.stdout, writer=server.stdin))

        # Request that the server initialize
        self._test_request(
            request_method=Method.INITIALIZE,
            request_params=dict(
                rootUri=f'file://{os.getcwd()}',
                capabilities=dict(),
                rootPath=os.getcwd(),
                clientInfo=dict(
                    name='test-language-server-client',
                    processId=os.getpid(),
                    trace='off'
                )
            ),
            expected_result=dict(
                capabilities=dict(
                    textDocumentSync=2, # Inc Sync
                    completionProvider=dict(
                        resolveProvider=False,
                        triggerCharacters=['.', '/', '@', "$", "*"]
                    )
                ),
                serverInfo=dict(
                    name="systemtap-language-server",
                    version="1.0"
                )
            )
        )

        # Send the server a notification that the initialization was successful.
        # NOTE: Notifications don't have results, we just check their side effects to ensure
        # correctness
        self._send_notification(notification_method=Method.INITIALIZED)

        textDocument = dict(
            uri='file://fake_doc.txt',
            languageId='systemtap',
            version=1,
            text='pr'
        )

        self._send_notification(
            notification_method=Method.TEXT_DOCUMENT_DID_OPEN,
            notification_params=dict(
                textDocument=textDocument
            )
        )

        # By changing the textDocument's text from pr to pro the completion request verifies
        # the change was correct since only 'probe' should be returned, not 'private' as well
        self._send_notification(
            notification_method=Method.TEXT_DOCUMENT_DID_CHANGE,
            notification_params=dict(
                textDocument=dict(
                    uri=textDocument['uri'],
                    version=textDocument['version']+1
                ),
                contentChanges=[dict(
                    text=textDocument['text'] + 'o',
                )]
            )
        )

        # Make sure the unknown methods don't cause issues
        response = self.server_conn.send_request(
            "foobar", dict())
        MethodNotFoundError = -32601
        self.assertEqual(response.get("error", {}).get(
            "code", -1), MethodNotFoundError)

        self._test_request(
            request_method=Method.COMPLETION,
            request_params=dict(
                textDocument=dict(
                    uri=textDocument['uri']
                ),
                position=dict(
                    character=3,
                    line=0
                )
            ),
            expected_result=dict(
                isIncomplete=False,
                items=[dict(
                    detail='keyword',
                    label='probe'
                )]
            )
        )

        self._send_notification(
            notification_method=Method.TEXT_DOCUMENT_DID_CLOSE,
            notification_params=dict(
                textDocument=dict(uri=textDocument['uri'])
            )
        )

        # Technically this should be a request, but its not an issue since we don't need a response here
        self._send_notification(notification_method=Method.SHUTDOWN)

        # Make sure the shutdown worked, since now only exit notifications should
        # be accepted and all others should error
        response = self.server_conn.send_request(
            Method.COMPLETION, dict())
        InvalidRequestError = -32600
        self.assertEqual(response.get("error", {}).get(
            "code", -1), InvalidRequestError)

        self._send_notification(Method.EXIT)

        ret_code = server.wait(timeout=10)
        self.assertEqual(ret_code, 0)


def test_suite(test_completion, test_integration):
    suite = unittest.TestSuite()
    if test_completion:
        suite.addTests([
            ServerCompletionTests('test_basic'),
            ServerCompletionTests('test_probe_comps'),
            ServerCompletionTests('test_string'),
            ServerCompletionTests('test_body'),
            ServerCompletionTests('test_multiple_contexts'),
            ServerCompletionTests('test_no_completions'),
            ServerCompletionTests('test_incremental_changes'),
            ServerCompletionTests('test_local_definitions'),
            ServerCompletionTests("test_target_vars")
        ])

    if test_integration:
        suite.addTest(ServerIntegrationTests('test_basic'))

    return suite


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.description = "Systemtap language server tests"
    parser.add_argument(
        "-v",
        "--verbose",
        help="increase verbosity of test",
        action="count",
        default=0,
    )
    parser.add_argument(
        "--stap-path",
        help="the path to the stap executable",
        type=str,
    )

    global CMD_ARGS
    CMD_ARGS = parser.parse_args()

    runner = unittest.TextTestRunner(failfast=True)
    ENV = dict(
        PATH=os.getenv("TEST_PATH"),
        TEST_C_FILE=os.getenv("TEST_C_FILE")
    )

    with mock.patch.dict(os.environ, ENV):
        res = runner.run(test_suite(
            test_completion=True, test_integration=True))
        sys.exit(0 if res.wasSuccessful() else 1)