-
Notifications
You must be signed in to change notification settings - Fork 50
/
rspecTests.ts
209 lines (183 loc) · 7.27 KB
/
rspecTests.ts
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
import * as vscode from 'vscode';
import { TestSuiteInfo, TestEvent } from 'vscode-test-adapter-api';
import * as childProcess from 'child_process';
import { Tests } from './tests';
export class RspecTests extends Tests {
testFrameworkName = 'RSpec';
/**
* Representation of the RSpec test suite as a TestSuiteInfo object.
*
* @return The RSpec test suite as a TestSuiteInfo object.
*/
tests = async () => new Promise<TestSuiteInfo>((resolve, reject) => {
try {
// If test suite already exists, use testSuite. Otherwise, load them.
let rspecTests = this.testSuite ? this.testSuite : this.loadTests();
return resolve(rspecTests);
} catch(err) {
this.log.error(`Error while attempting to load RSpec tests: ${err.message}`);
return reject(err);
}
});
/**
* Perform a dry-run of the test suite to get information about every test.
*
* @return The raw output from the RSpec JSON formatter.
*/
initTests = async () => new Promise<string>((resolve, reject) => {
let cmd = `${this.getTestCommand()} --require ${this.getCustomFormatterLocation()} --format CustomFormatter --order defined --dry-run`;
this.log.info(`Running dry-run of RSpec test suite with the following command: ${cmd}`);
// Allow a buffer of 64MB.
const execArgs: childProcess.ExecOptions = {
cwd: this.workspace.uri.fsPath,
maxBuffer: 8192 * 8192
};
childProcess.exec(cmd, execArgs, (err, stdout) => {
if (err) {
this.log.error(`Error while finding RSpec test suite: ${err.message}`);
// Show an error message.
vscode.window.showWarningMessage("Ruby Test Explorer failed to find an RSpec test suite. Make sure RSpec is installed and your configured RSpec command is correct.");
vscode.window.showErrorMessage(err.message);
throw err;
}
resolve(stdout);
});
});
/**
* Get the user-configured RSpec command, if there is one.
*
* @return The RSpec command
*/
protected getTestCommand(): string {
let command: string = (vscode.workspace.getConfiguration('rubyTestExplorer', null).get('rspecCommand') as string);
return command || 'bundle exec rspec';
}
/**
* Get the user-configured test directory, if there is one.
*
* @return The spec directory
*/
getTestDirectory(): string {
let directory: string = (vscode.workspace.getConfiguration('rubyTestExplorer', null).get('rspecDirectory') as string);
return directory || './spec/';
}
/**
* Get the absolute path of the custom_formatter.rb file.
*
* @return The spec directory
*/
protected getCustomFormatterLocation(): string {
return this.context.asAbsolutePath('./custom_formatter.rb');
}
/**
* Runs a single test.
*
* @param testLocation A file path with a line number, e.g. `/path/to/spec.rb:12`.
* @return The raw output from running the test.
*/
runSingleTest = async (testLocation: string) => new Promise<string>(async (resolve, reject) => {
this.log.info(`Running single test: ${testLocation}`);
const spawnArgs: childProcess.SpawnOptions = {
cwd: this.workspace.uri.fsPath,
shell: true
};
let testCommand = `${this.getTestCommand()} --require ${this.getCustomFormatterLocation()} --format CustomFormatter ${testLocation}`;
this.log.info(`Running command: ${testCommand}`);
let testProcess = childProcess.spawn(
testCommand,
spawnArgs
);
resolve(await this.handleChildProcess(testProcess));
});
/**
* Runs tests in a given file.
*
* @param testFile The test file's file path, e.g. `/path/to/spec.rb`.
* @return The raw output from running the tests.
*/
runTestFile = async (testFile: string) => new Promise<string>(async (resolve, reject) => {
this.log.info(`Running test file: ${testFile}`);
const spawnArgs: childProcess.SpawnOptions = {
cwd: this.workspace.uri.fsPath,
shell: true
};
// Run tests for a given file at once with a single command.
let testCommand = `${this.getTestCommand()} --require ${this.getCustomFormatterLocation()} --format CustomFormatter ${testFile}`;
this.log.info(`Running command: ${testCommand}`);
let testProcess = childProcess.spawn(
testCommand,
spawnArgs
);
resolve(await this.handleChildProcess(testProcess));
});
/**
* Runs the full test suite for the current workspace.
*
* @return The raw output from running the test suite.
*/
runFullTestSuite = async () => new Promise<string>(async (resolve, reject) => {
this.log.info(`Running full test suite.`);
const spawnArgs: childProcess.SpawnOptions = {
cwd: this.workspace.uri.fsPath,
shell: true
};
let testCommand = `${this.getTestCommand()} --require ${this.getCustomFormatterLocation()} --format CustomFormatter`;
this.log.info(`Running command: ${testCommand}`);
let testProcess = childProcess.spawn(
testCommand,
spawnArgs
);
resolve(await this.handleChildProcess(testProcess));
});
/**
* Handles test state based on the output returned by the custom RSpec formatter.
*
* @param test The test that we want to handle.
*/
handleStatus(test: any): void {
this.log.debug(`Handling status of test: ${JSON.stringify(test)}`);
if (test.status === "passed") {
this.testStatesEmitter.fire(<TestEvent>{ type: 'test', test: test.id, state: 'passed' });
} else if (test.status === "failed" && test.pending_message === null) {
// Remove linebreaks from error message.
let errorMessageNoLinebreaks = test.exception.message.replace(/(\r\n|\n|\r)/, ' ');
// Prepend the class name to the error message string.
let errorMessage: string = `${test.exception.class}:\n${errorMessageNoLinebreaks}`;
let fileBacktraceLineNumber: number | undefined;
let filePath = test.file_path.replace('./', '');
// Add backtrace to errorMessage if it exists.
if (test.exception.backtrace) {
errorMessage += `\n\nBacktrace:\n`;
test.exception.backtrace.forEach((line: string) => {
errorMessage += `${line}\n`;
// If the backtrace line includes the current file path, try to get the line number from it.
if (line.includes(filePath)) {
let filePathArray = filePath.split('/');
let fileName = filePathArray[filePathArray.length - 1];
// Input: spec/models/game_spec.rb:75:in `block (3 levels) in <top (required)>
// Output: 75
let regex = new RegExp(`${fileName}\:(\\d+)`);
let match = line.match(regex);
if (match && match[1]) {
fileBacktraceLineNumber = parseInt(match[1]);
}
}
});
}
this.testStatesEmitter.fire(<TestEvent>{
type: 'test',
test: test.id,
state: 'failed',
message: errorMessage,
decorations: [{
// Strip line breaks from the message.
message: errorMessageNoLinebreaks,
line: (fileBacktraceLineNumber ? fileBacktraceLineNumber : test.line_number) - 1
}]
});
} else if (test.status === "failed" && test.pending_message !== null) {
// Handle pending test cases.
this.testStatesEmitter.fire(<TestEvent>{ type: 'test', test: test.id, state: 'skipped', message: test.pending_message });
}
};
}