forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpytestExecutionAdapter.ts
More file actions
288 lines (263 loc) · 13.6 KB
/
pytestExecutionAdapter.ts
File metadata and controls
288 lines (263 loc) · 13.6 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { CancellationTokenSource, DebugSessionOptions, TestRun, TestRunProfileKind, Uri } from 'vscode';
import * as path from 'path';
import { ChildProcess } from 'child_process';
import { IConfigurationService } from '../../../common/types';
import { Deferred } from '../../../common/utils/async';
import { traceError, traceInfo, traceVerbose } from '../../../logging';
import { ExecutionTestPayload, ITestExecutionAdapter, ITestResultResolver } from '../common/types';
import {
ExecutionFactoryCreateWithEnvironmentOptions,
IPythonExecutionFactory,
SpawnOptions,
} from '../../../common/process/types';
import { removePositionalFoldersAndFiles } from './arguments';
import { ITestDebugLauncher, LaunchOptions } from '../../common/types';
import { PYTEST_PROVIDER } from '../../common/constants';
import { EXTENSION_ROOT_DIR } from '../../../common/constants';
import * as utils from '../common/utils';
import { IEnvironmentVariablesProvider } from '../../../common/variables/types';
import { PythonEnvironment } from '../../../pythonEnvironments/info';
import { getEnvironment, runInBackground, useEnvExtension } from '../../../envExt/api.internal';
export class PytestTestExecutionAdapter implements ITestExecutionAdapter {
constructor(
public configSettings: IConfigurationService,
private readonly resultResolver?: ITestResultResolver,
private readonly envVarsService?: IEnvironmentVariablesProvider,
) {}
async runTests(
uri: Uri,
testIds: string[],
profileKind: boolean | TestRunProfileKind | undefined,
runInstance: TestRun,
executionFactory: IPythonExecutionFactory,
debugLauncher?: ITestDebugLauncher,
interpreter?: PythonEnvironment,
): Promise<void> {
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(() => {
traceInfo(`Test run cancelled, resolving 'TillServerClose' deferred for ${uri.fsPath}.`);
});
try {
await this.runTestsNew(
uri,
testIds,
name,
cSource,
runInstance,
profileKind,
executionFactory,
debugLauncher,
interpreter,
);
} 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,
interpreter?: PythonEnvironment,
): Promise<ExecutionTestPayload> {
const relativePathToPytest = 'python_files';
const fullPluginPath = path.join(EXTENSION_ROOT_DIR, relativePathToPytest);
const settings = this.configSettings.getSettings(uri);
const { pytestArgs } = settings.testing;
const cwd = settings.testing.cwd && settings.testing.cwd.length > 0 ? settings.testing.cwd : uri.fsPath;
// get and edit env vars
const mutableEnv = {
...(await this.envVarsService?.getEnvironmentVariables(uri)),
};
// get python path from mutable env, it contains process.env as well
const pythonPathParts: string[] = mutableEnv.PYTHONPATH?.split(path.delimiter) ?? [];
const pythonPathCommand = [fullPluginPath, ...pythonPathParts].join(path.delimiter);
mutableEnv.PYTHONPATH = pythonPathCommand;
mutableEnv.TEST_RUN_PIPE = resultNamedPipeName;
if (profileKind && profileKind === TestRunProfileKind.Coverage) {
mutableEnv.COVERAGE_ENABLED = 'True';
}
const debugBool = profileKind && profileKind === TestRunProfileKind.Debug;
// Create the Python environment in which to execute the command.
const creationOptions: ExecutionFactoryCreateWithEnvironmentOptions = {
allowEnvironmentFetchExceptions: false,
resource: uri,
interpreter,
};
// need to check what will happen in the exec service is NOT defined and is null
const execService = await executionFactory.createActivatedEnvironment(creationOptions);
const execInfo = await execService?.getExecutablePath();
traceVerbose(`Executable path for pytest execution: ${execInfo}.`);
try {
// Remove positional test folders and files, we will add as needed per node
let testArgs = removePositionalFoldersAndFiles(pytestArgs);
// if user has provided `--rootdir` then use that, otherwise add `cwd`
// root dir is required so pytest can find the relative paths and for symlinks
utils.addValueIfKeyNotExist(testArgs, '--rootdir', cwd);
// -s and --capture are both command line options that control how pytest captures output.
// if neither are set, then set --capture=no to prevent pytest from capturing output.
if (debugBool && !utils.argKeyExists(testArgs, '-s')) {
testArgs = utils.addValueIfKeyNotExist(testArgs, '--capture', 'no');
}
// create a file with the test ids and set the environment variable to the file name
const testIdsFileName = await utils.writeTestIdsFile(testIds);
mutableEnv.RUN_TEST_IDS_PIPE = testIdsFileName;
traceInfo(
`Environment variables set for pytest execution: PYTHONPATH=${mutableEnv.PYTHONPATH}, TEST_RUN_PIPE=${mutableEnv.TEST_RUN_PIPE}, RUN_TEST_IDS_PIPE=${mutableEnv.RUN_TEST_IDS_PIPE}`,
);
const spawnOptions: SpawnOptions = {
cwd,
throwOnStdErr: true,
env: mutableEnv,
token: runInstance.token,
};
if (debugBool) {
const launchOptions: LaunchOptions = {
cwd,
args: testArgs,
token: runInstance.token,
testProvider: PYTEST_PROVIDER,
runTestIdsPort: testIdsFileName,
pytestPort: resultNamedPipeName,
};
const sessionOptions: DebugSessionOptions = {
testRun: runInstance,
};
traceInfo(`Running DEBUG pytest with arguments: ${testArgs} for workspace ${uri.fsPath} \r\n`);
await debugLauncher!.launchDebugger(
launchOptions,
() => {
serverCancel.cancel();
},
sessionOptions,
);
} else if (useEnvExtension()) {
const pythonEnv = await getEnvironment(uri);
if (pythonEnv) {
const deferredTillExecClose: Deferred<void> = utils.createTestingDeferred();
const scriptPath = path.join(fullPluginPath, 'vscode_pytest', 'run_pytest_script.py');
const runArgs = [scriptPath, ...testArgs];
traceInfo(`Running pytest with arguments: ${runArgs.join(' ')} for workspace ${uri.fsPath} \r\n`);
const proc = await runInBackground(pythonEnv, {
cwd,
args: runArgs,
env: (mutableEnv as unknown) as { [key: string]: string },
});
runInstance.token.onCancellationRequested(() => {
traceInfo(`Test run cancelled, killing pytest 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 {
// deferredTillExecClose is resolved when all stdout and stderr is read
const deferredTillExecClose: Deferred<void> = utils.createTestingDeferred();
// combine path to run script with run args
const scriptPath = path.join(fullPluginPath, 'vscode_pytest', 'run_pytest_script.py');
const runArgs = [scriptPath, ...testArgs];
traceInfo(`Running pytest with arguments: ${runArgs.join(' ')} for workspace ${uri.fsPath} \r\n`);
let resultProc: ChildProcess | undefined;
runInstance.token.onCancellationRequested(() => {
traceInfo(`Test run cancelled, killing pytest subprocess for workspace ${uri.fsPath}`);
// 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(runArgs, spawnOptions);
// Take all output from the subprocess and add it to the test output channel. This will be the pytest output.
// Displays output to user and ensure the subprocess doesn't run into buffer overflow.
result?.proc?.stdout?.on('data', (data) => {
const out = utils.fixLogLinesNoTrailing(data.toString());
runInstance.appendOutput(out);
});
result?.proc?.stderr?.on('data', (data) => {
const out = utils.fixLogLinesNoTrailing(data.toString());
runInstance.appendOutput(out);
});
result?.proc?.on('exit', (code, signal) => {
if (code !== 0) {
traceError(
`Subprocess exited unsuccessfully with exit code ${code} and signal ${signal} on workspace ${uri.fsPath}`,
);
}
});
result?.proc?.on('close', (code, signal) => {
traceVerbose('Test run finished, subprocess closed.');
// if the child has testIds then this is a run request
// if the child process exited with a non-zero exit code, then we need to send the error payload.
if (code !== 0) {
traceError(
`Subprocess closed unsuccessfully with exit code ${code} and signal ${signal} for workspace ${uri.fsPath}. Creating and sending error execution payload \n`,
);
if (runInstance) {
this.resultResolver?.resolveExecution(
utils.createExecutionErrorPayload(code, signal, testIds, cwd),
runInstance,
);
}
}
// deferredTillEOT is resolved when all data sent on stdout and stderr is received, close event is only called when this occurs
// due to the sync reading of the output.
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);
}
const executionPayload: ExecutionTestPayload = {
cwd,
status: 'success',
error: '',
};
return executionPayload;
}
}