File: runners.py

package info (click to toggle)
debugpy 1.8.12%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,424 kB
  • sloc: python: 14,451; sh: 184; makefile: 33
file content (348 lines) | stat: -rw-r--r-- 10,643 bytes parent folder | download
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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.

"""Runners are recipes for executing Targets in a debug.Session.

Every function in this module that is decorated with @_runner must have at least two
positional arguments: (session, target) - and can have additional arguments. For every
such function, two artifacts are produced.

The function is exposed directly as a method on Session, with the session argument
becoming self.

The function is also exposed as a Runner object from this module. Runner objects are
callable, and invoke the wrapped function when called, but in addition, they can also
be bound to specific arguments, by using either [] or with_options(), which can be
chained arbitrarily::

    # Direct invocation:
    session.attach_connect("cli", log_dir="...")

    # Indirect invocation:
    run = runners.attach_connect
    run = run["cli"]
    run = run.with_options(log_dir="...")
    run(session, target)

runner[x][y][z] is just a convenient shorthand for binding positional arguments, same
as runner.with_options(x, y, z).

Runners are immutable, so every use of [] or with_options() creates a new runner with
the specified arguments bound. The runner must have all its required arguments bound
before it can be invoked.

Regardless of whether the runner is invoked directly on the Session, or via a Runner
object, if the start DAP sequence involves a configuration phase (the "initialized"
event and the "configurationDone" request), the runner must be used in a with-statement.
The statements inside the with-statement are executed after receiving the "initialized"
event, and before sending the "configurationDone" request::

    with run(session, target):
        # DAP requests can be made to session, but target is not running yet.
        session.set_breakpoints(...)
    # target is running now!

If there is no configuration phase, the runner returns directly::

    session.config["noDebug"] = True
    run(session, target)
    # target is running now!
"""

import contextlib
import os
import pytest
import sys

import debugpy
from debugpy.common import json, log
from tests import net, timeline
from tests.debug import session
from tests.patterns import some


def _runner(f):
    # assert f.__name__.startswith("launch") or f.__name__.startswith("attach")
    setattr(session.Session, f.__name__, f)

    class Runner(object):
        request = "launch" if f.__name__.startswith("launch") else "attach"

        def __init__(self, *args, **kwargs):
            self._args = tuple(args)
            self._kwargs = dict(kwargs)

        def __getattr__(self, name):
            return self._kwargs[name]

        def __call__(self, session, target, *args, **kwargs):
            if len(args) or len(kwargs):
                return self.with_options(*args, **kwargs)(session, target)
            return f(session, target, *self._args, **self._kwargs)

        def __iter__(self):
            # Since we implement __getitem__, iter() will assume that runners are
            # iterable, and will iterate over them by calling __getitem__ until it
            # raises IndexError - i.e. indefinitely. To prevent that, explicitly
            # implement __iter__ as unsupported.
            raise NotImplementedError

        def __getitem__(self, arg):
            return self.with_options(arg)

        def with_options(self, *args, **kwargs):
            new_args = self._args + args
            new_kwargs = dict(self._kwargs)
            new_kwargs.update(kwargs)
            return Runner(*new_args, **new_kwargs)

        def __repr__(self):
            result = type(self).__name__
            args = [str(x) for x in self._args] + [
                f"{k}={v}" for k, v in self._kwargs.items()
            ]
            if len(args):
                result += "(" + ", ".join(args) + ")"
            return result

        @property
        def pytest_id(self):
            return repr(self)

    Runner.__name__ = f.__name__
    return Runner()


@_runner
def launch(session, target, console=None, cwd=None):
    assert console in (
        None,
        "internalConsole",
        "integratedTerminal",
        "externalTerminal",
    )

    log.info("Launching {0} in {1} using {2}.", target, session, json.repr(console))

    target.configure(session)
    config = session.config
    config.setdefaults(
        {"console": "externalTerminal", "internalConsoleOptions": "neverOpen"}
    )
    if console is not None:
        config["console"] = console
    if cwd is not None:
        config["cwd"] = cwd
    if "python" not in config and "pythonPath" not in config:
        config["python"] = sys.executable

    env = (
        session.spawn_adapter.env
        if config["console"] == "internalConsole"
        else config.env
    )
    target.cli(env)

    session.spawn_adapter()
    return session.request_launch()


def _attach_common_config(session, target, cwd):
    assert (
        target.code is None or "debuggee.setup()" in target.code
    ), f"{target.filename} must invoke debuggee.setup()."

    target.configure(session)
    config = session.config
    if cwd is not None:
        config.setdefault("pathMappings", [{"localRoot": cwd, "remoteRoot": "."}])
    return config


@_runner
@contextlib.contextmanager
def attach_pid(session, target, cwd=None, wait=True):
    if wait and not sys.platform.startswith("linux"):
        pytest.skip("https://github.com/microsoft/ptvsd/issues/1926")

    log.info("Attaching {0} to {1} by PID.", session, target)

    config = session.config
    try:
        config["processId"] = int(target)
    except TypeError:
        pass

    if "processId" not in config:
        _attach_common_config(session, target, cwd)
        args = target.cli(session.spawn_debuggee.env)

        if wait:
            debuggee_setup = """
import sys
import threading
import time

while "debugpy" not in sys.modules:
    time.sleep(0.1)

from debuggee import scratchpad

while "_attach_pid" not in scratchpad:
    time.sleep(0.1)
    """
        else:
            debuggee_setup = None

        session.spawn_debuggee(args, cwd=cwd, setup=debuggee_setup)
        config["processId"] = session.debuggee.pid

    session.spawn_adapter()
    session.expect_server_socket()
    with session.request_attach():
        yield

    if wait:
        session.scratchpad["_attach_pid"] = True


@_runner
def attach_connect(session, target, method, cwd=None, wait=True, log_dir=None):
    log.info(
        "Attaching {0} to {1} by socket using {2}.", session, target, method.upper()
    )

    assert method in ("api", "cli")

    config = _attach_common_config(session, target, cwd)
    config["connect"] = {}
    config["connect"]["host"] = host = attach_connect.host
    config["connect"]["port"] = port = attach_connect.port

    if method == "cli":
        args = [
            os.path.dirname(debugpy.__file__),
            "--listen",
            f"{host}:{port}",
        ]
        if wait:
            args += ["--wait-for-client"]
        if log_dir is not None:
            args += ["--log-to", log_dir]
        if "subProcess" in config:
            args += ["--configure-subProcess", str(config["subProcess"])]
        debuggee_setup = None
    elif method == "api":
        args = []
        api_config = {k: v for k, v in config.items() if k in {"subProcess"}}
        debuggee_setup = """
import debugpy
if {log_dir!r}:
    debugpy.log_to({log_dir!r})
debugpy.configure({api_config!r})
debugpy.listen(({host!r}, {port!r}))
if {wait!r}:
    debugpy.wait_for_client()
"""
        debuggee_setup = debuggee_setup.format(
            host=host,
            port=port,
            wait=wait,
            log_dir=log_dir,
            api_config=api_config,
        )
    else:
        raise ValueError
    args += target.cli(session.spawn_debuggee.env)

    try:
        del config["subProcess"]
    except KeyError:
        pass

    # If adapter is connecting to the client, the server is already started,
    # so it should be reported in the initial event.
    session.expect_server_socket()

    session.spawn_debuggee(args, cwd=cwd, setup=debuggee_setup)
    session.wait_for_adapter_socket()
    session.connect_to_adapter((host, port))
    return session.request_attach()


attach_connect.host = "127.0.0.1"
attach_connect.port = net.get_test_server_port()


@_runner
def attach_listen(session, target, method, cwd=None, log_dir=None):
    log.info(
        "Attaching {0} to {1} by socket using {2}.", session, target, method.upper()
    )

    assert method in ("api", "cli")

    config = _attach_common_config(session, target, cwd)
    config["listen"] = {}
    config["listen"]["host"] = host = attach_listen.host
    config["listen"]["port"] = port = attach_listen.port

    if method == "cli":
        args = [
            os.path.dirname(debugpy.__file__),
            "--connect",
            f"{host}:{port}",
        ]
        if log_dir is not None:
            args += ["--log-to", log_dir]
        if "subProcess" in config:
            args += ["--configure-subProcess", str(config["subProcess"])]
        debuggee_setup = None
    elif method == "api":
        args = []
        api_config = {k: v for k, v in config.items() if k in {"subProcess"}}
        debuggee_setup = f"""
import debugpy
if {log_dir!r}:
    debugpy.log_to({log_dir!r})
debugpy.configure({api_config!r})
debugpy.connect({(host, port)!r})
"""
    else:
        raise ValueError
    args += target.cli(session.spawn_debuggee.env)

    try:
        del config["subProcess"]
    except KeyError:
        pass

    def spawn_debuggee(occ):
        assert occ.body == some.dict.containing({"host": host, "port": port})
        session.spawn_debuggee(args, cwd=cwd, setup=debuggee_setup)

    session.timeline.when(timeline.Event("debugpyWaitingForServer"), spawn_debuggee)
    session.spawn_adapter(args=[] if log_dir is None else ["--log-dir", log_dir])
    return session.request_attach()


attach_listen.host = "127.0.0.1"
attach_listen.port = net.get_test_server_port()

all_launch_terminal = [
    launch.with_options(console="integratedTerminal"),
    launch.with_options(console="externalTerminal"),
]

all_launch = [launch.with_options(console="internalConsole")] + all_launch_terminal

all_attach_listen = [attach_listen["api"], attach_listen["cli"]]

all_attach_connect = [attach_connect["api"], attach_connect["cli"]]

all_attach_socket = all_attach_listen + all_attach_connect

all_attach = all_attach_socket + [attach_pid]

all = all_launch + all_attach