forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdebugLauncher.ts
More file actions
375 lines (339 loc) · 15.5 KB
/
debugLauncher.ts
File metadata and controls
375 lines (339 loc) · 15.5 KB
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
import { inject, injectable, named } from 'inversify';
import * as path from 'path';
import { DebugConfiguration, l10n, Uri, WorkspaceFolder, DebugSession, DebugSessionOptions, Disposable } from 'vscode';
import { IApplicationShell, IDebugService } from '../../common/application/types';
import { EXTENSION_ROOT_DIR } from '../../common/constants';
import * as internalScripts from '../../common/process/internal/scripts';
import { IConfigurationService, IPythonSettings } from '../../common/types';
import { DebuggerTypeName, PythonDebuggerTypeName } from '../../debugger/constants';
import { IDebugConfigurationResolver } from '../../debugger/extension/configuration/types';
import { DebugPurpose, LaunchRequestArguments } from '../../debugger/types';
import { IServiceContainer } from '../../ioc/types';
import { traceError, traceVerbose } from '../../logging';
import { TestProvider } from '../types';
import { ITestDebugLauncher, LaunchOptions } from './types';
import { getConfigurationsForWorkspace } from '../../debugger/extension/configuration/launch.json/launchJsonReader';
import { getWorkspaceFolder, getWorkspaceFolders } from '../../common/vscodeApis/workspaceApis';
import { showErrorMessage } from '../../common/vscodeApis/windowApis';
import { createDeferred } from '../../common/utils/async';
import { addPathToPythonpath } from './helpers';
import * as envExtApi from '../../envExt/api.internal';
/**
* Key used to mark debug configurations with a unique session identifier.
* This allows us to track which debug session belongs to which launchDebugger() call
* when multiple debug sessions are launched in parallel.
*/
const TEST_SESSION_MARKER_KEY = '__vscodeTestSessionMarker';
@injectable()
export class DebugLauncher implements ITestDebugLauncher {
private readonly configService: IConfigurationService;
constructor(
@inject(IServiceContainer) private serviceContainer: IServiceContainer,
@inject(IDebugConfigurationResolver)
@named('launch')
private readonly launchResolver: IDebugConfigurationResolver<LaunchRequestArguments>,
) {
this.configService = this.serviceContainer.get<IConfigurationService>(IConfigurationService);
}
/**
* Launches a debug session for test execution.
*
* **Cancellation handling:**
* Cancellation can occur from multiple sources, all properly handled:
* 1. **Pre-check**: If already cancelled before starting, returns immediately
* 2. **Token cancellation**: If the parent CancellationToken fires during debugging,
* the deferred resolves and the callback is invoked to clean up resources
* 3. **Session termination**: When the user stops debugging (via UI or completes),
* the onDidTerminateDebugSession event fires and we resolve
*
* **Multi-session support:**
* When debugging tests from multiple projects simultaneously, each launchDebugger()
* call needs to track its own debug session independently. We use a unique marker
* in the launch configuration to identify which session belongs to which call,
* avoiding race conditions with the global `activeDebugSession` property.
*
* @param options Launch configuration including test provider, args, and optional project info
* @param callback Called when the debug session ends (for cleanup like closing named pipes)
* @param sessionOptions VS Code debug session options (e.g., testRun association)
*/
public async launchDebugger(
options: LaunchOptions,
callback?: () => void,
sessionOptions?: DebugSessionOptions,
): Promise<void> {
const deferred = createDeferred<void>();
let hasCallbackBeenCalled = false;
// Collect disposables for cleanup when debugging completes
const disposables: Disposable[] = [];
// Ensure callback is only invoked once, even if multiple termination paths fire
const callCallbackOnce = () => {
if (!hasCallbackBeenCalled) {
hasCallbackBeenCalled = true;
callback?.();
}
};
// Early exit if already cancelled before we start
if (options.token && options.token.isCancellationRequested) {
callCallbackOnce();
deferred.resolve();
return deferred.promise;
}
// Listen for cancellation from the test run (e.g., user clicks stop in Test Explorer)
// This allows the caller to clean up resources even if the debug session is still running
if (options.token) {
disposables.push(
options.token.onCancellationRequested(() => {
deferred.resolve();
callCallbackOnce();
}),
);
}
const workspaceFolder = DebugLauncher.resolveWorkspaceFolder(options.cwd);
const launchArgs = await this.getLaunchArgs(
options,
workspaceFolder,
this.configService.getSettings(workspaceFolder.uri),
);
const debugManager = this.serviceContainer.get<IDebugService>(IDebugService);
// Generate a unique marker for this debug session.
// When multiple debug sessions start in parallel (e.g., debugging tests from
// multiple projects), we can't rely on debugManager.activeDebugSession because
// it's a global that could be overwritten by another concurrent session start.
// Instead, we embed a unique marker in our launch configuration and match it
// when the session starts to identify which session is ours.
const sessionMarker = `test-${Date.now()}-${Math.random().toString(36).substring(7)}`;
launchArgs[TEST_SESSION_MARKER_KEY] = sessionMarker;
let ourSession: DebugSession | undefined;
// Capture our specific debug session when it starts by matching the marker.
// This fires for ALL debug sessions, so we filter to only our marker.
disposables.push(
debugManager.onDidStartDebugSession((session) => {
if (session.configuration[TEST_SESSION_MARKER_KEY] === sessionMarker) {
ourSession = session;
traceVerbose(`[test-debug] Debug session started: ${session.name} (${session.id})`);
}
}),
);
// Handle debug session termination (user stops debugging, or tests complete).
// Only react to OUR session terminating - other parallel sessions should
// continue running independently.
disposables.push(
debugManager.onDidTerminateDebugSession((session) => {
if (ourSession && session.id === ourSession.id) {
traceVerbose(`[test-debug] Debug session terminated: ${session.name} (${session.id})`);
deferred.resolve();
callCallbackOnce();
}
}),
);
// Start the debug session
const started = await debugManager.startDebugging(workspaceFolder, launchArgs, sessionOptions);
if (!started) {
traceError('Failed to start debug session');
deferred.resolve();
callCallbackOnce();
}
// Clean up event subscriptions when debugging completes (success, failure, or cancellation)
deferred.promise.finally(() => {
disposables.forEach((d) => d.dispose());
});
return deferred.promise;
}
private static resolveWorkspaceFolder(cwd: string): WorkspaceFolder {
const hasWorkspaceFolders = (getWorkspaceFolders()?.length || 0) > 0;
if (!hasWorkspaceFolders) {
throw new Error('Please open a workspace');
}
const cwdUri = cwd ? Uri.file(cwd) : undefined;
let workspaceFolder = getWorkspaceFolder(cwdUri);
if (!workspaceFolder) {
const [first] = getWorkspaceFolders()!;
workspaceFolder = first;
}
return workspaceFolder;
}
private async getLaunchArgs(
options: LaunchOptions,
workspaceFolder: WorkspaceFolder,
configSettings: IPythonSettings,
): Promise<LaunchRequestArguments> {
let debugConfig = await DebugLauncher.readDebugConfig(workspaceFolder);
if (!debugConfig) {
debugConfig = {
name: 'Debug Unit Test',
type: 'debugpy',
request: 'test',
subProcess: true,
};
}
// Use project name in debug session name if provided
if (options.project) {
debugConfig.name = `Debug Tests: ${options.project.name}`;
}
if (!debugConfig.rules) {
debugConfig.rules = [];
}
debugConfig.rules.push({
path: path.join(EXTENSION_ROOT_DIR, 'python_files'),
include: false,
});
DebugLauncher.applyDefaults(debugConfig!, workspaceFolder, configSettings);
return this.convertConfigToArgs(debugConfig!, workspaceFolder, options);
}
public async readAllDebugConfigs(workspace: WorkspaceFolder): Promise<DebugConfiguration[]> {
try {
const configs = await getConfigurationsForWorkspace(workspace);
return configs;
} catch (exc) {
traceError('could not get debug config', exc);
const appShell = this.serviceContainer.get<IApplicationShell>(IApplicationShell);
await appShell.showErrorMessage(
l10n.t('Could not load unit test config from launch.json as it is missing a field'),
);
return [];
}
}
private static async readDebugConfig(
workspaceFolder: WorkspaceFolder,
): Promise<LaunchRequestArguments | undefined> {
try {
const configs = await getConfigurationsForWorkspace(workspaceFolder);
for (const cfg of configs) {
if (
cfg.name &&
(cfg.type === DebuggerTypeName || cfg.type === PythonDebuggerTypeName) &&
(cfg.request === 'test' ||
(cfg as LaunchRequestArguments).purpose?.includes(DebugPurpose.DebugTest))
) {
// Return the first one.
return cfg as LaunchRequestArguments;
}
}
return undefined;
} catch (exc) {
traceError('could not get debug config', exc);
await showErrorMessage(l10n.t('Could not load unit test config from launch.json as it is missing a field'));
return undefined;
}
}
private static applyDefaults(
cfg: LaunchRequestArguments,
workspaceFolder: WorkspaceFolder,
configSettings: IPythonSettings,
) {
// cfg.pythonPath is handled by LaunchConfigurationResolver.
if (!cfg.console) {
cfg.console = 'internalConsole';
}
if (!cfg.cwd) {
cfg.cwd = configSettings.testing.cwd || workspaceFolder.uri.fsPath;
}
if (!cfg.env) {
cfg.env = {};
}
if (!cfg.envFile) {
cfg.envFile = configSettings.envFile;
}
if (cfg.stopOnEntry === undefined) {
cfg.stopOnEntry = false;
}
cfg.showReturnValue = cfg.showReturnValue !== false;
if (cfg.redirectOutput === undefined) {
cfg.redirectOutput = true;
}
if (cfg.debugStdLib === undefined) {
cfg.debugStdLib = false;
}
if (cfg.subProcess === undefined) {
cfg.subProcess = true;
}
}
private async convertConfigToArgs(
debugConfig: LaunchRequestArguments,
workspaceFolder: WorkspaceFolder,
options: LaunchOptions,
): Promise<LaunchRequestArguments> {
const configArgs = debugConfig as LaunchRequestArguments;
const testArgs =
options.testProvider === 'unittest' ? options.args.filter((item) => item !== '--debug') : options.args;
const script = DebugLauncher.getTestLauncherScript(options.testProvider);
const args = script(testArgs);
const [program] = args;
configArgs.program = program;
configArgs.args = args.slice(1);
// We leave configArgs.request as "test" so it will be sent in telemetry.
let launchArgs = await this.launchResolver.resolveDebugConfiguration(
workspaceFolder,
configArgs,
options.token,
);
if (!launchArgs) {
throw Error(`Invalid debug config "${debugConfig.name}"`);
}
launchArgs = await this.launchResolver.resolveDebugConfigurationWithSubstitutedVariables(
workspaceFolder,
launchArgs,
options.token,
);
if (!launchArgs) {
throw Error(`Invalid debug config "${debugConfig.name}"`);
}
launchArgs.request = 'launch';
if (options.pytestPort && options.runTestIdsPort) {
launchArgs.env = {
...launchArgs.env,
TEST_RUN_PIPE: options.pytestPort,
RUN_TEST_IDS_PIPE: options.runTestIdsPort,
};
} else {
throw Error(
`Missing value for debug setup, both port and uuid need to be defined. port: "${options.pytestPort}" uuid: "${options.pytestUUID}"`,
);
}
const pluginPath = path.join(EXTENSION_ROOT_DIR, 'python_files');
// check if PYTHONPATH is already set in the environment variables
if (launchArgs.env) {
const additionalPythonPath = [pluginPath];
if (launchArgs.cwd) {
additionalPythonPath.push(launchArgs.cwd);
} else if (options.cwd) {
additionalPythonPath.push(options.cwd);
}
// add the plugin path or cwd to PYTHONPATH if it is not already there using the following function
// this function will handle if PYTHONPATH is undefined
addPathToPythonpath(additionalPythonPath, launchArgs.env.PYTHONPATH);
}
// Clear out purpose so we can detect if the configuration was used to
// run via F5 style debugging.
launchArgs.purpose = [];
// For project-based execution, get the Python path from the project's environment.
// This ensures debug sessions use the correct interpreter for each project.
if (options.project && envExtApi.useEnvExtension()) {
try {
const pythonEnv = await envExtApi.getEnvironment(options.project.uri);
if (pythonEnv?.execInfo?.run?.executable) {
launchArgs.python = pythonEnv.execInfo.run.executable;
traceVerbose(
`[test-by-project] Debug session using Python path from project: ${launchArgs.python}`,
);
}
} catch (error) {
traceVerbose(`[test-by-project] Could not get environment for project, using default: ${error}`);
}
}
return launchArgs;
}
private static getTestLauncherScript(testProvider: TestProvider) {
switch (testProvider) {
case 'unittest': {
return internalScripts.execution_py_testlauncher; // this is the new way to run unittest execution, debugger
}
case 'pytest': {
return internalScripts.pytestlauncher; // this is the new way to run pytest execution, debugger
}
default: {
throw new Error(`Unknown test provider '${testProvider}'`);
}
}
}
}