forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.ts
More file actions
211 lines (193 loc) · 9.34 KB
/
runner.ts
File metadata and controls
211 lines (193 loc) · 9.34 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
'use strict';
import { inject, injectable } from 'inversify';
import * as path from 'path';
import { EXTENSION_ROOT_DIR } from '../../common/constants';
import { IDisposableRegistry, ILogger } from '../../common/types';
import { createDeferred, Deferred } from '../../common/utils/async';
import { noop } from '../../common/utils/misc';
import { IServiceContainer } from '../../ioc/types';
import { UNITTEST_PROVIDER } from '../common/constants';
import { Options } from '../common/runner';
import {
ITestDebugLauncher, ITestManager, ITestResultsService,
ITestRunner, IUnitTestSocketServer, LaunchOptions,
TestRunOptions, Tests, TestStatus
} from '../common/types';
import { IArgumentsHelper, ITestManagerRunner, IUnitTestHelper } from '../types';
type TestStatusMap = {
status: TestStatus;
summaryProperty: 'passed' | 'failures' | 'errors' | 'skipped';
};
const outcomeMapping = new Map<string, TestStatusMap>();
outcomeMapping.set('passed', { status: TestStatus.Pass, summaryProperty: 'passed' });
outcomeMapping.set('failed', { status: TestStatus.Fail, summaryProperty: 'failures' });
outcomeMapping.set('error', { status: TestStatus.Error, summaryProperty: 'errors' });
outcomeMapping.set('skipped', { status: TestStatus.Skipped, summaryProperty: 'skipped' });
interface ITestData {
test: string;
message: string;
outcome: string;
traceback: string;
}
@injectable()
export class TestManagerRunner implements ITestManagerRunner {
private readonly argsHelper: IArgumentsHelper;
private readonly helper: IUnitTestHelper;
private readonly testRunner: ITestRunner;
private readonly server: IUnitTestSocketServer;
private readonly logger: ILogger;
private busy!: Deferred<Tests>;
constructor(@inject(IServiceContainer) private serviceContainer: IServiceContainer) {
this.argsHelper = serviceContainer.get<IArgumentsHelper>(IArgumentsHelper);
this.testRunner = serviceContainer.get<ITestRunner>(ITestRunner);
this.server = this.serviceContainer.get<IUnitTestSocketServer>(IUnitTestSocketServer);
this.logger = this.serviceContainer.get<ILogger>(ILogger);
this.helper = this.serviceContainer.get<IUnitTestHelper>(IUnitTestHelper);
this.serviceContainer.get<IDisposableRegistry>(IDisposableRegistry).push(this.server);
}
// tslint:disable-next-line:max-func-body-length
public async runTest(testResultsService: ITestResultsService, options: TestRunOptions, testManager: ITestManager): Promise<Tests> {
if (this.busy && !this.busy.completed) {
return this.busy.promise;
}
this.busy = createDeferred<Tests>();
options.tests.summary.errors = 0;
options.tests.summary.failures = 0;
options.tests.summary.passed = 0;
options.tests.summary.skipped = 0;
let failFast = false;
const testLauncherFile = path.join(EXTENSION_ROOT_DIR, 'pythonFiles', 'visualstudio_py_testlauncher.py');
this.server.on('error', (message: string, ...data: string[]) => this.logger.logError(`${message} ${data.join(' ')}`));
this.server.on('log', noop);
this.server.on('connect', noop);
this.server.on('start', noop);
this.server.on('result', (data: ITestData) => {
const test = options.tests.testFunctions.find(t => t.testFunction.nameToRun === data.test);
const statusDetails = outcomeMapping.get(data.outcome)!;
if (test) {
test.testFunction.status = statusDetails.status;
switch (test.testFunction.status) {
case TestStatus.Error:
case TestStatus.Fail: {
test.testFunction.passed = false;
break;
}
case TestStatus.Pass: {
test.testFunction.passed = true;
break;
}
default: {
test.testFunction.passed = undefined;
}
}
test.testFunction.message = data.message;
test.testFunction.traceback = data.traceback;
options.tests.summary[statusDetails.summaryProperty] += 1;
if (failFast && (statusDetails.summaryProperty === 'failures' || statusDetails.summaryProperty === 'errors')) {
testManager.stop();
}
} else {
if (statusDetails) {
options.tests.summary[statusDetails.summaryProperty] += 1;
}
}
});
const port = await this.server.start();
const testPaths: string[] = this.helper.getIdsOfTestsToRun(options.tests, options.testsToRun!);
for (let counter = 0; counter < testPaths.length; counter += 1) {
testPaths[counter] = `-t${testPaths[counter].trim()}`;
}
const runTestInternal = async (testFile: string = '', testId: string = '') => {
let testArgs = this.buildTestArgs(options.args);
failFast = testArgs.indexOf('--uf') >= 0;
testArgs = testArgs.filter(arg => arg !== '--uf');
testArgs.push(`--result-port=${port}`);
if (testId.length > 0) {
testArgs.push(`-t${testId}`);
}
if (testFile.length > 0) {
testArgs.push(`--testFile=${testFile}`);
}
if (options.debug === true) {
const debugLauncher = this.serviceContainer.get<ITestDebugLauncher>(ITestDebugLauncher);
testArgs.push('--debug');
const launchOptions: LaunchOptions = { cwd: options.cwd, args: testArgs, token: options.token, outChannel: options.outChannel, testProvider: UNITTEST_PROVIDER };
return debugLauncher.launchDebugger(launchOptions);
} else {
const runOptions: Options = {
args: [testLauncherFile].concat(testArgs),
cwd: options.cwd,
outChannel: options.outChannel,
token: options.token,
workspaceFolder: options.workspaceFolder
};
await this.testRunner.run(UNITTEST_PROVIDER, runOptions);
}
};
// Test everything.
if (testPaths.length === 0) {
await this.removeListenersAfter(runTestInternal());
} else {
// Ok, the test runner can only work with one test at a time.
if (options.testsToRun) {
if (Array.isArray(options.testsToRun.testFile)) {
for (const testFile of options.testsToRun.testFile) {
await runTestInternal(testFile.fullPath, testFile.nameToRun);
}
}
if (Array.isArray(options.testsToRun.testSuite)) {
for (const testSuite of options.testsToRun.testSuite) {
const item = options.tests.testSuites.find(t => t.testSuite === testSuite);
if (item) {
const testFileName = item.parentTestFile.fullPath;
await runTestInternal(testFileName, testSuite.nameToRun);
}
}
}
if (Array.isArray(options.testsToRun.testFunction)) {
for (const testFn of options.testsToRun.testFunction) {
const item = options.tests.testFunctions.find(t => t.testFunction === testFn);
if (item) {
const testFileName = item.parentTestFile.fullPath;
await runTestInternal(testFileName, testFn.nameToRun);
}
}
}
await this.removeListenersAfter(Promise.resolve());
}
}
testResultsService.updateResults(options.tests);
this.busy.resolve(options.tests);
return options.tests;
}
// remove all the listeners from the server after all tests are complete,
// and just pass the promise `after` through as we do not want to get in
// the way here.
// tslint:disable-next-line:no-any
private async removeListenersAfter(after: Promise<any>): Promise<any> {
return after
.then(() => this.server.removeAllListeners())
.catch((err) => {
this.server.removeAllListeners();
throw err; // keep propagating this downward
});
}
private buildTestArgs(args: string[]): string[] {
const startTestDiscoveryDirectory = this.helper.getStartDirectory(args);
let pattern = 'test*.py';
const shortValue = this.argsHelper.getOptionValues(args, '-p');
const longValueValue = this.argsHelper.getOptionValues(args, '-pattern');
if (typeof shortValue === 'string') {
pattern = shortValue;
} else if (typeof longValueValue === 'string') {
pattern = longValueValue;
}
const failFast = args.some(arg => arg.trim() === '-f' || arg.trim() === '--failfast');
const verbosity = args.some(arg => arg.trim().indexOf('-v') === 0) ? 2 : 1;
const testArgs = [`--us=${startTestDiscoveryDirectory}`, `--up=${pattern}`, `--uvInt=${verbosity}`];
if (failFast) {
testArgs.push('--uf');
}
return testArgs;
}
}