File: TestVSCode_variables.py

package info (click to toggle)
llvm-toolchain-14 1%3A14.0.6-12
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,496,180 kB
  • sloc: cpp: 5,593,972; ansic: 986,872; asm: 585,869; python: 184,223; objc: 72,530; lisp: 31,119; f90: 27,793; javascript: 9,780; pascal: 9,762; sh: 9,482; perl: 7,468; ml: 5,432; awk: 3,523; makefile: 2,538; xml: 953; cs: 573; fortran: 567
file content (410 lines) | stat: -rw-r--r-- 17,918 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
"""
Test lldb-vscode setBreakpoints request
"""

from __future__ import print_function

import unittest2
import vscode
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
import lldbvscode_testcase


def make_buffer_verify_dict(start_idx, count, offset=0):
    verify_dict = {}
    for i in range(start_idx, start_idx + count):
        verify_dict['[%i]' % (i)] = {'type': 'int', 'value': str(i+offset)}
    return verify_dict


class TestVSCode_variables(lldbvscode_testcase.VSCodeTestCaseBase):

    mydir = TestBase.compute_mydir(__file__)

    def verify_values(self, verify_dict, actual, varref_dict=None, expression=None):
        if 'equals' in verify_dict:
            verify = verify_dict['equals']
            for key in verify:
                verify_value = verify[key]
                actual_value = actual[key]
                self.assertEqual(verify_value, actual_value,
                                '"%s" keys don\'t match (%s != %s)' % (
                                    key, actual_value, verify_value))
        if 'startswith' in verify_dict:
            verify = verify_dict['startswith']
            for key in verify:
                verify_value = verify[key]
                actual_value = actual[key]
                startswith = actual_value.startswith(verify_value)
                self.assertTrue(startswith,
                                ('"%s" value "%s" doesn\'t start with'
                                 ' "%s")') % (
                                    key, actual_value,
                                    verify_value))
        hasVariablesReference = 'variablesReference' in actual
        varRef = None
        if hasVariablesReference:
            # Remember variable references in case we want to test further
            # by using the evaluate name.
            varRef = actual["variablesReference"]
            if varRef != 0 and varref_dict is not None:
                if expression is None:
                    evaluateName = actual["evaluateName"]
                else:
                    evaluateName = expression
                varref_dict[evaluateName] = varRef
        if ('hasVariablesReference' in verify_dict and
                verify_dict['hasVariablesReference']):
            self.assertTrue(hasVariablesReference,
                            "verify variable reference")
        if 'children' in verify_dict:
            self.assertTrue(hasVariablesReference and varRef is not None and
                            varRef != 0,
                            ("children verify values specified for "
                             "variable without children"))

            response = self.vscode.request_variables(varRef)
            self.verify_variables(verify_dict['children'],
                                  response['body']['variables'],
                                  varref_dict)

    def verify_variables(self, verify_dict, variables, varref_dict=None):
        for variable in variables:
            name = variable['name']
            self.assertIn(name, verify_dict,
                          'variable "%s" in verify dictionary' % (name))
            self.verify_values(verify_dict[name], variable, varref_dict)

    @skipIfWindows
    @skipIfRemote
    def test_scopes_variables_setVariable_evaluate(self):
        '''
            Tests the "scopes", "variables", "setVariable", and "evaluate"
            packets.
        '''
        program = self.getBuildArtifact("a.out")
        self.build_and_launch(program)
        source = 'main.cpp'
        breakpoint1_line = line_number(source, '// breakpoint 1')
        lines = [breakpoint1_line]
        # Set breakpoint in the thread function so we can step the threads
        breakpoint_ids = self.set_source_breakpoints(source, lines)
        self.assertEqual(len(breakpoint_ids), len(lines),
                        "expect correct number of breakpoints")
        self.continue_to_breakpoints(breakpoint_ids)
        locals = self.vscode.get_local_variables()
        globals = self.vscode.get_global_variables()
        buffer_children = make_buffer_verify_dict(0, 32)
        verify_locals = {
            'argc': {
                'equals': {'type': 'int', 'value': '1'}
            },
            'argv': {
                'equals': {'type': 'const char **'},
                'startswith': {'value': '0x'},
                'hasVariablesReference': True
            },
            'pt': {
                'equals': {'type': 'PointType'},
                'hasVariablesReference': True,
                'children': {
                    'x': {'equals': {'type': 'int', 'value': '11'}},
                    'y': {'equals': {'type': 'int', 'value': '22'}},
                    'buffer': {'children': buffer_children}
                }
            },
            'x': {
                'equals': {'type': 'int'}
            }
        }
        verify_globals = {
            's_local': {
                'equals': {'type': 'float', 'value': '2.25'}
            },
            '::g_global': {
                'equals': {'type': 'int', 'value': '123'}
            },
            's_global': {
                'equals': {'type': 'int', 'value': '234'}
            },
        }
        varref_dict = {}
        self.verify_variables(verify_locals, locals, varref_dict)
        self.verify_variables(verify_globals, globals, varref_dict)
        # pprint.PrettyPrinter(indent=4).pprint(varref_dict)
        # We need to test the functionality of the "variables" request as it
        # has optional parameters like "start" and "count" to limit the number
        # of variables that are fetched
        varRef = varref_dict['pt.buffer']
        response = self.vscode.request_variables(varRef)
        self.verify_variables(buffer_children, response['body']['variables'])
        # Verify setting start=0 in the arguments still gets all children
        response = self.vscode.request_variables(varRef, start=0)
        self.verify_variables(buffer_children, response['body']['variables'])
        # Verify setting count=0 in the arguments still gets all children.
        # If count is zero, it means to get all children.
        response = self.vscode.request_variables(varRef, count=0)
        self.verify_variables(buffer_children, response['body']['variables'])
        # Verify setting count to a value that is too large in the arguments
        # still gets all children, and no more
        response = self.vscode.request_variables(varRef, count=1000)
        self.verify_variables(buffer_children, response['body']['variables'])
        # Verify setting the start index and count gets only the children we
        # want
        response = self.vscode.request_variables(varRef, start=5, count=5)
        self.verify_variables(make_buffer_verify_dict(5, 5),
                              response['body']['variables'])
        # Verify setting the start index to a value that is out of range
        # results in an empty list
        response = self.vscode.request_variables(varRef, start=32, count=1)
        self.assertEqual(len(response['body']['variables']), 0,
                        'verify we get no variable back for invalid start')

        # Test evaluate
        expressions = {
            'pt.x': {
                'equals': {'result': '11', 'type': 'int'},
                'hasVariablesReference': False
            },
            'pt.buffer[2]': {
                'equals': {'result': '2', 'type': 'int'},
                'hasVariablesReference': False
            },
            'pt': {
                'equals': {'type': 'PointType'},
                'startswith': {'result': 'PointType @ 0x'},
                'hasVariablesReference': True
            },
            'pt.buffer': {
                'equals': {'type': 'int[32]'},
                'startswith': {'result': 'int[32] @ 0x'},
                'hasVariablesReference': True
            },
            'argv': {
                'equals': {'type': 'const char **'},
                'startswith': {'result': '0x'},
                'hasVariablesReference': True
            },
            'argv[0]': {
                'equals': {'type': 'const char *'},
                'startswith': {'result': '0x'},
                'hasVariablesReference': True
            },
            '2+3': {
                'equals': {'result': '5', 'type': 'int'},
                'hasVariablesReference': False
            },
        }
        for expression in expressions:
            response = self.vscode.request_evaluate(expression)
            self.verify_values(expressions[expression], response['body'])

        # Test setting variables
        self.set_local('argc', 123)
        argc = self.get_local_as_int('argc')
        self.assertEqual(argc, 123,
                        'verify argc was set to 123 (123 != %i)' % (argc))

        self.set_local('argv', 0x1234)
        argv = self.get_local_as_int('argv')
        self.assertEqual(argv, 0x1234,
                        'verify argv was set to 0x1234 (0x1234 != %#x)' % (
                            argv))

        # Set a variable value whose name is synthetic, like a variable index
        # and verify the value by reading it
        self.vscode.request_setVariable(varRef, "[0]", 100)
        response = self.vscode.request_variables(varRef, start=0, count=1)
        self.verify_variables(make_buffer_verify_dict(0, 1, 100),
                              response['body']['variables'])

        # Set a variable value whose name is a real child value, like "pt.x"
        # and verify the value by reading it
        varRef = varref_dict['pt']
        self.vscode.request_setVariable(varRef, "x", 111)
        response = self.vscode.request_variables(varRef, start=0, count=1)
        value = response['body']['variables'][0]['value']
        self.assertEqual(value, '111',
                        'verify pt.x got set to 111 (111 != %s)' % (value))

        # We check shadowed variables and that a new get_local_variables request
        # gets the right data
        breakpoint2_line = line_number(source, '// breakpoint 2')
        lines = [breakpoint2_line]
        breakpoint_ids = self.set_source_breakpoints(source, lines)
        self.assertEqual(len(breakpoint_ids), len(lines),
                        "expect correct number of breakpoints")
        self.continue_to_breakpoints(breakpoint_ids)

        verify_locals['argc']['equals']['value'] = '123'
        verify_locals['pt']['children']['x']['equals']['value'] = '111'
        verify_locals['x @ main.cpp:17'] = {'equals': {'type': 'int', 'value': '89'}}
        verify_locals['x @ main.cpp:19'] = {'equals': {'type': 'int', 'value': '42'}}
        verify_locals['x @ main.cpp:21'] = {'equals': {'type': 'int', 'value': '72'}}

        self.verify_variables(verify_locals, self.vscode.get_local_variables())

        # Now we verify that we correctly change the name of a variable with and without differentiator suffix
        self.assertFalse(self.vscode.request_setVariable(1, "x2", 9)['success'])
        self.assertFalse(self.vscode.request_setVariable(1, "x @ main.cpp:0", 9)['success'])

        self.assertTrue(self.vscode.request_setVariable(1, "x @ main.cpp:17", 17)['success'])
        self.assertTrue(self.vscode.request_setVariable(1, "x @ main.cpp:19", 19)['success'])
        self.assertTrue(self.vscode.request_setVariable(1, "x @ main.cpp:21", 21)['success'])

        # The following should have no effect
        self.assertFalse(self.vscode.request_setVariable(1, "x @ main.cpp:21", "invalid")['success'])

        verify_locals['x @ main.cpp:17']['equals']['value'] = '17'
        verify_locals['x @ main.cpp:19']['equals']['value'] = '19'
        verify_locals['x @ main.cpp:21']['equals']['value'] = '21'

        self.verify_variables(verify_locals, self.vscode.get_local_variables())

        # The plain x variable shold refer to the innermost x
        self.assertTrue(self.vscode.request_setVariable(1, "x", 22)['success'])
        verify_locals['x @ main.cpp:21']['equals']['value'] = '22'

        self.verify_variables(verify_locals, self.vscode.get_local_variables())

        # In breakpoint 3, there should be no shadowed variables
        breakpoint3_line = line_number(source, '// breakpoint 3')
        lines = [breakpoint3_line]
        breakpoint_ids = self.set_source_breakpoints(source, lines)
        self.assertEqual(len(breakpoint_ids), len(lines),
                        "expect correct number of breakpoints")
        self.continue_to_breakpoints(breakpoint_ids)

        locals = self.vscode.get_local_variables()
        names = [var['name'] for var in locals]
        # The first shadowed x shouldn't have a suffix anymore
        verify_locals['x'] = {'equals': {'type': 'int', 'value': '17'}}
        self.assertNotIn('x @ main.cpp:17', names)
        self.assertNotIn('x @ main.cpp:19', names)
        self.assertNotIn('x @ main.cpp:21', names)

        self.verify_variables(verify_locals, locals)

    @skipIfWindows
    @skipIfRemote
    def test_scopes_and_evaluate_expansion(self):
        """
        Tests the evaluated expression expands successfully after "scopes" packets
        and permanent expressions persist.
        """
        program = self.getBuildArtifact("a.out")
        self.build_and_launch(program)
        source = "main.cpp"
        breakpoint1_line = line_number(source, "// breakpoint 1")
        lines = [breakpoint1_line]
        # Set breakpoint in the thread function so we can step the threads
        breakpoint_ids = self.set_source_breakpoints(source, lines)
        self.assertEqual(
            len(breakpoint_ids), len(lines), "expect correct number of breakpoints"
        )
        self.continue_to_breakpoints(breakpoint_ids)

        # Verify locals
        locals = self.vscode.get_local_variables()
        buffer_children = make_buffer_verify_dict(0, 32)
        verify_locals = {
            "argc": {"equals": {"type": "int", "value": "1"}},
            "argv": {
                "equals": {"type": "const char **"},
                "startswith": {"value": "0x"},
                "hasVariablesReference": True,
            },
            "pt": {
                "equals": {"type": "PointType"},
                "hasVariablesReference": True,
                "children": {
                    "x": {"equals": {"type": "int", "value": "11"}},
                    "y": {"equals": {"type": "int", "value": "22"}},
                    "buffer": {"children": buffer_children},
                },
            },
            "x": {"equals": {"type": "int"}},
        }
        self.verify_variables(verify_locals, locals)

        # Evaluate expandable expression twice: once permanent (from repl)
        # the other temporary (from other UI).
        expandable_expression = {
            "name": "pt",
            "response": {
                "equals": {"type": "PointType"},
                "startswith": {"result": "PointType @ 0x"},
                "hasVariablesReference": True,
            },
            "children": {
                "x": {"equals": {"type": "int", "value": "11"}},
                "y": {"equals": {"type": "int", "value": "22"}},
                "buffer": {"children": buffer_children},
            },
        }

        # Evaluate from permanent UI.
        permanent_expr_varref_dict = {}
        response = self.vscode.request_evaluate(
            expandable_expression["name"], frameIndex=0, threadId=None, context="repl"
        )
        self.verify_values(
            expandable_expression["response"],
            response["body"],
            permanent_expr_varref_dict,
            expandable_expression["name"],
        )

        # Evaluate from temporary UI.
        temporary_expr_varref_dict = {}
        response = self.vscode.request_evaluate(expandable_expression["name"])
        self.verify_values(
            expandable_expression["response"],
            response["body"],
            temporary_expr_varref_dict,
            expandable_expression["name"],
        )

        # Evaluate locals again.
        locals = self.vscode.get_local_variables()
        self.verify_variables(verify_locals, locals)

        # Verify the evaluated expressions before second locals evaluation
        # can be expanded.
        var_ref = temporary_expr_varref_dict[expandable_expression["name"]]
        response = self.vscode.request_variables(var_ref)
        self.verify_variables(
            expandable_expression["children"], response["body"]["variables"]
        )

        # Continue to breakpoint 3, permanent variable should still exist
        # after resume.
        breakpoint3_line = line_number(source, "// breakpoint 3")
        lines = [breakpoint3_line]
        breakpoint_ids = self.set_source_breakpoints(source, lines)
        self.assertEqual(
            len(breakpoint_ids), len(lines), "expect correct number of breakpoints"
        )
        self.continue_to_breakpoints(breakpoint_ids)

        var_ref = permanent_expr_varref_dict[expandable_expression["name"]]
        response = self.vscode.request_variables(var_ref)
        self.verify_variables(
            expandable_expression["children"], response["body"]["variables"]
        )

        # Test that frame scopes have corresponding presentation hints.
        frame_id = self.vscode.get_stackFrame()["id"]
        scopes = self.vscode.request_scopes(frame_id)["body"]["scopes"]

        scope_names = [scope["name"] for scope in scopes]
        self.assertIn("Locals", scope_names)
        self.assertIn("Registers", scope_names)

        for scope in scopes:
            if scope["name"] == "Locals":
                self.assertEquals(scope.get("presentationHint"), "locals")
            if scope["name"] == "Registers":
                self.assertEquals(scope.get("presentationHint"), "registers")