forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtestExecutionAdapter.ts
More file actions
298 lines (272 loc) · 12.8 KB
/
testExecutionAdapter.ts
File metadata and controls
298 lines (272 loc) · 12.8 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as path from 'path';
import { CancellationTokenSource, DebugSessionOptions, TestRun, TestRunProfileKind, Uri } from 'vscode';
import { ChildProcess } from 'child_process';
import { IConfigurationService } from '../../../common/types';
import { Deferred, createDeferred } from '../../../common/utils/async';
import { EXTENSION_ROOT_DIR } from '../../../constants';
import {
ExecutionTestPayload,
ITestExecutionAdapter,
ITestResultResolver,
TestCommandOptions,
TestExecutionCommand,
} from '../common/types';
import { traceError, traceInfo, traceLog, traceVerbose } from '../../../logging';
import { fixLogLinesNoTrailing } from '../common/utils';
import { EnvironmentVariables, IEnvironmentVariablesProvider } from '../../../common/variables/types';
import {
ExecutionFactoryCreateWithEnvironmentOptions,
ExecutionResult,
IPythonExecutionFactory,
SpawnOptions,
} from '../../../common/process/types';
import { ITestDebugLauncher, LaunchOptions } from '../../common/types';
import { UNITTEST_PROVIDER } from '../../common/constants';
import * as utils from '../common/utils';
import { getEnvironment, runInBackground, useEnvExtension } from '../../../envExt/api.internal';
/**
* Wrapper Class for unittest test execution. This is where we call `runTestCommand`?
*/
export class UnittestTestExecutionAdapter implements ITestExecutionAdapter {
constructor(
public configSettings: IConfigurationService,
private readonly resultResolver?: ITestResultResolver,
private readonly envVarsService?: IEnvironmentVariablesProvider,
) {}
public async runTests(
uri: Uri,
testIds: string[],
profileKind: boolean | TestRunProfileKind | undefined,
runInstance: TestRun,
executionFactory: IPythonExecutionFactory,
debugLauncher?: ITestDebugLauncher,
): Promise<void> {
// deferredTillServerClose awaits named pipe server close
const deferredTillServerClose: Deferred<void> = utils.createTestingDeferred();
// create callback to handle data received on the named pipe
const dataReceivedCallback = (data: ExecutionTestPayload) => {
if (runInstance && !runInstance.token.isCancellationRequested) {
this.resultResolver?.resolveExecution(data, runInstance);
} else {
traceError(`No run instance found, cannot resolve execution, for workspace ${uri.fsPath}.`);
}
};
const cSource = new CancellationTokenSource();
runInstance.token.onCancellationRequested(() => cSource.cancel());
const name = await utils.startRunResultNamedPipe(
dataReceivedCallback, // callback to handle data received
deferredTillServerClose, // deferred to resolve when server closes
cSource.token, // token to cancel
);
runInstance.token.onCancellationRequested(() => {
console.log(`Test run cancelled, resolving 'till TillAllServerClose' deferred for ${uri.fsPath}.`);
// if canceled, stop listening for results
deferredTillServerClose.resolve();
});
try {
await this.runTestsNew(
uri,
testIds,
name,
cSource,
runInstance,
profileKind,
executionFactory,
debugLauncher,
);
} catch (error) {
traceError(`Error in running unittest tests: ${error}`);
} finally {
await deferredTillServerClose.promise;
}
}
private async runTestsNew(
uri: Uri,
testIds: string[],
resultNamedPipeName: string,
serverCancel: CancellationTokenSource,
runInstance: TestRun,
profileKind: boolean | TestRunProfileKind | undefined,
executionFactory: IPythonExecutionFactory,
debugLauncher?: ITestDebugLauncher,
): Promise<ExecutionTestPayload> {
const settings = this.configSettings.getSettings(uri);
const { unittestArgs } = settings.testing;
const cwd = settings.testing.cwd && settings.testing.cwd.length > 0 ? settings.testing.cwd : uri.fsPath;
const command = buildExecutionCommand(unittestArgs);
let mutableEnv: EnvironmentVariables | undefined = await this.envVarsService?.getEnvironmentVariables(uri);
if (mutableEnv === undefined) {
mutableEnv = {} as EnvironmentVariables;
}
const pythonPathParts: string[] = mutableEnv.PYTHONPATH?.split(path.delimiter) ?? [];
const pythonPathCommand = [cwd, ...pythonPathParts].join(path.delimiter);
mutableEnv.PYTHONPATH = pythonPathCommand;
mutableEnv.TEST_RUN_PIPE = resultNamedPipeName;
if (profileKind && profileKind === TestRunProfileKind.Coverage) {
mutableEnv.COVERAGE_ENABLED = cwd;
}
const options: TestCommandOptions = {
workspaceFolder: uri,
command,
cwd,
profileKind: typeof profileKind === 'boolean' ? undefined : profileKind,
testIds,
token: runInstance.token,
};
traceLog(`Running UNITTEST execution for the following test ids: ${testIds}`);
// create named pipe server to send test ids
const testIdsFileName = await utils.writeTestIdsFile(testIds);
mutableEnv.RUN_TEST_IDS_PIPE = testIdsFileName;
traceInfo(
`All environment variables set for unittest execution, PYTHONPATH: ${JSON.stringify(
mutableEnv.PYTHONPATH,
)}`,
);
const spawnOptions: SpawnOptions = {
token: options.token,
cwd: options.cwd,
throwOnStdErr: true,
env: mutableEnv,
};
// Create the Python environment in which to execute the command.
const creationOptions: ExecutionFactoryCreateWithEnvironmentOptions = {
allowEnvironmentFetchExceptions: false,
resource: options.workspaceFolder,
};
const execService = await executionFactory.createActivatedEnvironment(creationOptions);
const execInfo = await execService?.getExecutablePath();
traceVerbose(`Executable path for unittest execution: ${execInfo}.`);
const args = [options.command.script].concat(options.command.args);
if (options.outChannel) {
options.outChannel.appendLine(`python ${args.join(' ')}`);
}
try {
if (options.profileKind && options.profileKind === TestRunProfileKind.Debug) {
const launchOptions: LaunchOptions = {
cwd: options.cwd,
args,
token: options.token,
testProvider: UNITTEST_PROVIDER,
runTestIdsPort: testIdsFileName,
pytestPort: resultNamedPipeName, // change this from pytest
};
const sessionOptions: DebugSessionOptions = {
testRun: runInstance,
};
traceInfo(`Running DEBUG unittest for workspace ${options.cwd} with arguments: ${args}\r\n`);
if (debugLauncher === undefined) {
traceError('Debug launcher is not defined');
throw new Error('Debug launcher is not defined');
}
await debugLauncher.launchDebugger(
launchOptions,
() => {
serverCancel.cancel();
},
sessionOptions,
);
} else if (useEnvExtension()) {
const pythonEnv = await getEnvironment(uri);
if (pythonEnv) {
traceInfo(`Running unittest with arguments: ${args.join(' ')} for workspace ${uri.fsPath} \r\n`);
const deferredTillExecClose = createDeferred();
const proc = await runInBackground(pythonEnv, {
cwd,
args,
env: (mutableEnv as unknown) as { [key: string]: string },
});
runInstance.token.onCancellationRequested(() => {
traceInfo(`Test run cancelled, killing unittest subprocess for workspace ${uri.fsPath}`);
proc.kill();
deferredTillExecClose.resolve();
serverCancel.cancel();
});
proc.stdout.on('data', (data) => {
const out = utils.fixLogLinesNoTrailing(data.toString());
runInstance.appendOutput(out);
});
proc.stderr.on('data', (data) => {
const out = utils.fixLogLinesNoTrailing(data.toString());
runInstance.appendOutput(out);
});
proc.onExit((code, signal) => {
if (code !== 0) {
traceError(
`Subprocess exited unsuccessfully with exit code ${code} and signal ${signal} on workspace ${uri.fsPath}`,
);
}
deferredTillExecClose.resolve();
serverCancel.cancel();
});
await deferredTillExecClose.promise;
} else {
traceError(`Python Environment not found for: ${uri.fsPath}`);
}
} else {
// This means it is running the test
traceInfo(`Running unittests for workspace ${cwd} with arguments: ${args}\r\n`);
const deferredTillExecClose = createDeferred<ExecutionResult<string>>();
let resultProc: ChildProcess | undefined;
runInstance.token.onCancellationRequested(() => {
traceInfo(`Test run cancelled, killing unittest subprocess for workspace ${cwd}.`);
// if the resultProc exists just call kill on it which will handle resolving the ExecClose deferred, otherwise resolve the deferred here.
if (resultProc) {
resultProc?.kill();
} else {
deferredTillExecClose?.resolve();
serverCancel.cancel();
}
});
const result = execService?.execObservable(args, spawnOptions);
resultProc = result?.proc;
// Displays output to user and ensure the subprocess doesn't run into buffer overflow.
result?.proc?.stdout?.on('data', (data) => {
const out = fixLogLinesNoTrailing(data.toString());
runInstance.appendOutput(`${out}`);
});
result?.proc?.stderr?.on('data', (data) => {
const out = fixLogLinesNoTrailing(data.toString());
runInstance.appendOutput(`${out}`);
});
result?.proc?.on('exit', (code, signal) => {
// if the child has testIds then this is a run request
if (code !== 0 && testIds) {
// This occurs when we are running the test and there is an error which occurs.
traceError(
`Subprocess exited unsuccessfully with exit code ${code} and signal ${signal} for workspace ${options.cwd}. Creating and sending error execution payload \n`,
);
if (runInstance) {
this.resultResolver?.resolveExecution(
utils.createExecutionErrorPayload(code, signal, testIds, cwd),
runInstance,
);
}
}
deferredTillExecClose.resolve();
serverCancel.cancel();
});
await deferredTillExecClose.promise;
}
} catch (ex) {
traceError(`Error while running tests for workspace ${uri}: ${testIds}\r\n${ex}\r\n\r\n`);
return Promise.reject(ex);
}
// placeholder until after the rewrite is adopted
// TODO: remove after adoption.
const executionPayload: ExecutionTestPayload = {
cwd,
status: 'success',
error: '',
};
return executionPayload;
}
}
function buildExecutionCommand(args: string[]): TestExecutionCommand {
const executionScript = path.join(EXTENSION_ROOT_DIR, 'python_files', 'unittestadapter', 'execution.py');
return {
script: executionScript,
args: ['--udiscovery', ...args],
};
}