forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.refactor.extract.var.test.ts
More file actions
277 lines (254 loc) · 12.3 KB
/
extension.refactor.extract.var.test.ts
File metadata and controls
277 lines (254 loc) · 12.3 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
// Place this right on top
import { initialize, closeActiveWindows } from './initialize';
/// <reference path="../../node_modules/@types/mocha/index.d.ts" />
import * as assert from 'assert';
// You can import and use all API from the \'vscode\' module
// as well as import your extension to test it
import * as vscode from 'vscode';
import { TextDocument, TextLine, Position, Range } from 'vscode';
import * as path from 'path';
import * as settings from '../client/common/configSettings';
import * as fs from 'fs-extra';
import { execPythonFile } from '../client/common/utils';
import { extractVariable } from '../client/providers/simpleRefactorProvider';
import { RefactorProxy } from '../client/refactor/proxy';
import { getTextEditsFromPatch } from '../client/common/editor';
let EXTENSION_DIR = path.join(__dirname, '..', '..');
let pythonSettings = settings.PythonSettings.getInstance();
const refactorSourceFile = path.join(__dirname, '..', '..', 'src', 'test', 'pythonFiles', 'refactoring', 'standAlone', 'refactor.py');
const refactorTargetFile = path.join(__dirname, '..', '..', 'out', 'test', 'pythonFiles', 'refactoring', 'standAlone', 'refactor.py');
let isPython3 = true;
let isTRAVIS = (process.env['TRAVIS'] + '') === 'true';
interface RenameResponse {
results: [{ diff: string }];
}
class MockOutputChannel implements vscode.OutputChannel {
constructor(name: string) {
this.name = name;
this.output = '';
}
name: string;
output: string;
append(value: string) {
this.output += value;
}
appendLine(value: string) { this.append(value); this.append('\n'); }
clear() { }
show(preservceFocus?: boolean): void;
show(column?: vscode.ViewColumn, preserveFocus?: boolean): void;
show(x?: any, y?: any): void { }
hide() { }
dispose() { }
}
class MockTextDocument implements vscode.TextDocument {
uri: vscode.Uri;
fileName: string;
isUntitled: boolean;
languageId: string;
version: number;
isDirty: boolean;
offsets: [{ position: Position, offset: number }];
constructor(private sourceFile: string) {
this.lineCount = fs.readFileSync(this.sourceFile, 'utf8').split(/\r?\n/g).length;
this.offsets = [
{ position: new vscode.Position(234, 20), offset: 8191 },
{ position: new vscode.Position(234, 29), offset: 8200 },
{ position: new vscode.Position(234, 38), offset: 8209 }
];
}
save(): Thenable<boolean> {
return Promise.resolve(true);
}
lineCount: number;
lineAt(position: Position | number): TextLine {
let lineNumber: number = position as number;
if ((position as Position).line) {
lineNumber = (position as Position).line;
}
let line = fs.readFileSync(this.sourceFile, 'utf8').split(/\r?\n/g)[lineNumber];
return <TextLine>{ isEmptyOrWhitespace: line.trim().length > 0 };
}
offsetAt(position: Position): number {
return this.offsets.filter(item => item.position.isEqual(position))[0].offset;
}
positionAt(offset: number): Position {
return null;
}
getText(range?: Range): string {
return fs.readFileSync(this.sourceFile, 'utf8');
}
getWordRangeAtPosition(position: Position): Range {
return null;
}
validateRange(range: Range): Range {
return null;
}
validatePosition(position: Position): Position {
return null;
}
}
suiteSetup(done => {
fs.copySync(refactorSourceFile, refactorTargetFile, { clobber: true });
initialize().then(() => {
new Promise<string>(resolve => {
// Support for travis
let version = process.env['TRAVIS_PYTHON_VERSION'];
if (typeof version === 'string') {
return resolve(version);
}
// Support for local tests
execPythonFile('python', ['--version'], __dirname, true).then(resolve);
}).then(version => {
isPython3 = version.indexOf('3.') >= 0;
done();
});
});
});
suiteTeardown(done => {
// deleteFile(targetPythonFileToLint).then(done, done);
done();
});
suite('Variable Extraction', () => {
setup(() => {
if (fs.existsSync(refactorTargetFile)) {
fs.unlinkSync(refactorTargetFile);
}
fs.copySync(refactorSourceFile, refactorTargetFile, { clobber: true });
});
teardown(done => {
closeActiveWindows().then(() => {
setTimeout(function () {
done();
}, 1000);
});
});
function testingVariableExtraction(shouldError: boolean, pythonSettings: settings.IPythonSettings, startPos: Position, endPos: Position) {
let rangeOfTextToExtract = new vscode.Range(startPos, endPos);
let proxy = new RefactorProxy(EXTENSION_DIR, pythonSettings, path.dirname(refactorTargetFile));
let mockTextDoc = new MockTextDocument(refactorTargetFile);
let ignoreErrorHandling = false;
const DIFF = '--- a/refactor.py\n+++ b/refactor.py\n@@ -232,7 +232,8 @@\n sys.stdout.flush()\n \n def watch(self):\n- self._write_response("STARTED")\n+ myNewVariable = "STARTED"\n+ self._write_response(myNewVariable)\n while True:\n try:\n self._process_request(self._input.readline())\n';
let expectedTextEdits = getTextEditsFromPatch(mockTextDoc.getText(), DIFF);
return proxy.extractVariable<RenameResponse>(mockTextDoc, 'myNewVariable', refactorTargetFile, rangeOfTextToExtract)
.then(response => {
if (shouldError) {
ignoreErrorHandling = true;
assert.fail(null, null, 'Extraction should fail with an error', '');
}
let textEdits = getTextEditsFromPatch(mockTextDoc.getText(), DIFF);
assert.equal(response.results.length, 1, 'Invalid number of items in response');
assert.equal(textEdits.length, expectedTextEdits.length, 'Invalid number of Text Edits');
textEdits.forEach(edit => {
let foundEdit = expectedTextEdits.filter(item => item.newText === edit.newText && item.range.isEqual(edit.range));
assert.equal(foundEdit.length, 1, 'Edit not found');
});
}).catch(error => {
if (ignoreErrorHandling) {
return Promise.reject(error);
}
if (shouldError) {
// Wait a minute this shouldn't work, what's going on
assert.equal(true, true, 'Error raised as expected');
return;
}
return Promise.reject(error);
});
}
test('Extract Variable', done => {
let startPos = new vscode.Position(234, 29);
let endPos = new vscode.Position(234, 38);
testingVariableExtraction(false, pythonSettings, startPos, endPos).then(() => done(), done);
});
test('Extract Variable fails if whole string not selected', done => {
let startPos = new vscode.Position(234, 20);
let endPos = new vscode.Position(234, 38);
testingVariableExtraction(true, pythonSettings, startPos, endPos).then(() => done(), done);
});
test('Extract Variable will try to find Python 2.x', done => {
let startPos = new vscode.Position(234, 29);
let endPos = new vscode.Position(234, 38);
let clonedSettings = JSON.parse(JSON.stringify(pythonSettings));
testingVariableExtraction(false, clonedSettings, startPos, endPos).then(() => done(), done);
});
// test('Extract Variable will not work in Python 3.x', done => {
// let startPos = new vscode.Position(234, 29);
// let endPos = new vscode.Position(234, 38);
// let clonedSettings = JSON.parse(JSON.stringify(pythonSettings));
// clonedSettings.pythonPath = 'python3';
// testingVariableExtraction(true, clonedSettings, startPos, endPos).then(() => done(), done);
// });
if (!isTRAVIS) {
function testingVariableExtractionEndToEnd(shouldError: boolean, pythonSettings: settings.IPythonSettings, startPos: Position, endPos: Position) {
let ch = new MockOutputChannel('Python');
let textDocument: vscode.TextDocument;
let textEditor: vscode.TextEditor;
let rangeOfTextToExtract = new vscode.Range(startPos, endPos);
let ignoreErrorHandling = false;
return vscode.workspace.openTextDocument(refactorTargetFile).then(document => {
textDocument = document;
return vscode.window.showTextDocument(textDocument);
}).then(editor => {
editor.selections = [new vscode.Selection(rangeOfTextToExtract.start, rangeOfTextToExtract.end)];
editor.selection = new vscode.Selection(rangeOfTextToExtract.start, rangeOfTextToExtract.end);
textEditor = editor;
return;
}).then(() => {
return extractVariable(EXTENSION_DIR, textEditor, rangeOfTextToExtract, ch, path.dirname(refactorTargetFile), pythonSettings).then(() => {
if (shouldError) {
ignoreErrorHandling = true;
assert.fail('No error', 'Error', 'Extraction should fail with an error', '');
}
assert.equal(ch.output.length, 0, 'Output channel is not empty');
assert.equal(textDocument.lineAt(234).text.trim().indexOf('newvariable'), 0, 'New Variable not created');
assert.equal(textDocument.lineAt(234).text.trim().endsWith('= "STARTED"'), true, 'Started Text Assigned to variable');
assert.equal(textDocument.lineAt(235).text.indexOf('(newvariable') >= 0, true, 'New Variable not being used');
}).catch(error => {
if (ignoreErrorHandling) {
return Promise.reject(error);
}
if (shouldError) {
// Wait a minute this shouldn't work, what's going on
assert.equal(true, true, 'Error raised as expected');
return;
}
return Promise.reject(error);
});
}, error => {
if (ignoreErrorHandling) {
return Promise.reject(error);
}
if (shouldError) {
// Wait a minute this shouldn't work, what's going on
assert.equal(true, true, 'Error raised as expected');
}
else {
assert.fail(error + '', null, 'Variable extraction failed\n' + ch.output, '');
return Promise.reject(error);
}
});
}
test('Extract Variable (end to end)', done => {
let startPos = new vscode.Position(234, 29);
let endPos = new vscode.Position(234, 38);
testingVariableExtractionEndToEnd(false, pythonSettings, startPos, endPos).then(() => done(), done);
});
test('Extract Variable fails if whole string not selected (end to end)', done => {
let startPos = new vscode.Position(234, 20);
let endPos = new vscode.Position(234, 38);
testingVariableExtractionEndToEnd(true, pythonSettings, startPos, endPos).then(() => done(), done);
});
test('Extract Variable will try to find Python 2.x (end to end)', done => {
let startPos = new vscode.Position(234, 29);
let endPos = new vscode.Position(234, 38);
let clonedSettings = JSON.parse(JSON.stringify(pythonSettings));
testingVariableExtractionEndToEnd(false, clonedSettings, startPos, endPos).then(() => done(), done);
});
// test('Extract Variable will not work in Python 3.x (end to end)', done => {
// let startPos = new vscode.Position(234, 29);
// let endPos = new vscode.Position(234, 38);
// let clonedSettings = JSON.parse(JSON.stringify(pythonSettings));
// clonedSettings.pythonPath = 'python3';
// testingVariableExtractionEndToEnd(true, clonedSettings, startPos, endPos).then(() => done(), done);
// });
}
});