forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.lineFormatter.test.ts
More file actions
248 lines (233 loc) · 10.1 KB
/
extension.lineFormatter.test.ts
File metadata and controls
248 lines (233 loc) · 10.1 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as assert from 'assert';
import * as fs from 'fs';
import * as path from 'path';
import * as TypeMoq from 'typemoq';
import { Position, Range, TextDocument, TextLine } from 'vscode';
import '../../client/common/extensions';
import { LineFormatter } from '../../client/formatters/lineFormatter';
const formatFilesPath = path.join(__dirname, '..', '..', '..', 'src', 'test', 'pythonFiles', 'formatting');
const grammarFile = path.join(formatFilesPath, 'pythonGrammar.py');
// https://www.python.org/dev/peps/pep-0008/#code-lay-out
// tslint:disable-next-line:max-func-body-length
suite('Formatting - line formatter', () => {
const formatter = new LineFormatter();
test('Operator spacing', () => {
testFormatLine('( x +1 )*y/ 3', '(x + 1) * y / 3');
});
test('Braces spacing', () => {
testFormatMultiline('foo =(0 ,)', 0, 'foo = (0,)');
});
test('Colon regular', () => {
testFormatMultiline('if x == 4 : print x,y; x,y= y, x', 0, 'if x == 4: print x, y; x, y = y, x');
});
test('Colon slices', () => {
testFormatLine('x[1: 30]', 'x[1:30]');
});
test('Colon slices in arguments', () => {
testFormatLine('spam ( ham[ 1 :3], {eggs : 2})', 'spam(ham[1:3], {eggs: 2})');
});
test('Colon slices with double colon', () => {
testFormatLine(
'ham [1:9 ], ham[ 1: 9: 3], ham[: 9 :3], ham[1: :3], ham [ 1: 9:]',
'ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]'
);
});
test('Colon slices with operators', () => {
testFormatLine('ham [lower+ offset :upper+offset]', 'ham[lower + offset:upper + offset]');
});
test('Colon slices with functions', () => {
testFormatLine(
'ham[ : upper_fn ( x) : step_fn(x )], ham[ :: step_fn(x)]',
'ham[:upper_fn(x):step_fn(x)], ham[::step_fn(x)]'
);
});
test('Colon in for loop', () => {
testFormatLine('for index in range( len(fruits) ): ', 'for index in range(len(fruits)):');
});
test('Nested braces', () => {
testFormatLine('[ 1 :[2: (x,),y]]{1}', '[1:[2:(x,), y]]{1}');
});
test('Trailing comment', () => {
testFormatMultiline('x=1 # comment', 0, 'x = 1 # comment');
});
test('Single comment', () => {
testFormatLine('# comment', '# comment');
});
test('Comment with leading whitespace', () => {
testFormatLine(' # comment', ' # comment');
});
test('Operators without following space', () => {
testFormatLine('foo( *a, ** b, ! c)', 'foo(*a, **b, !c)');
});
test('Brace after keyword', () => {
testFormatLine('for x in(1,2,3)', 'for x in (1, 2, 3)');
testFormatLine('assert(1,2,3)', 'assert (1, 2, 3)');
testFormatLine('if (True|False)and(False/True)not (! x )', 'if (True | False) and (False / True) not (!x)');
testFormatLine('while (True|False)', 'while (True | False)');
testFormatLine('yield(a%b)', 'yield (a % b)');
});
test('Dot operator', () => {
testFormatLine('x.y', 'x.y');
testFormatLine('5 .y', '5.y');
});
test('Unknown tokens no space', () => {
testFormatLine('abc\\n\\', 'abc\\n\\');
});
test('Unknown tokens with space', () => {
testFormatLine('abc \\n \\', 'abc \\n \\');
});
test('Double asterisk', () => {
testFormatLine('a**2, ** k', 'a ** 2, **k');
});
test('Lambda', () => {
testFormatLine('lambda * args, :0', 'lambda *args,: 0');
});
test('Comma expression', () => {
testFormatMultiline('x=1,2,3', 0, 'x = 1, 2, 3');
});
test('is exression', () => {
testFormatLine('a( (False is 2) is 3)', 'a((False is 2) is 3)');
});
test('Function returning tuple', () => {
testFormatMultiline('x,y=f(a)', 0, 'x, y = f(a)');
});
test('from. import A', () => {
testFormatLine('from. import A', 'from . import A');
});
test('from .. import', () => {
testFormatLine('from ..import', 'from .. import');
});
test('from..x import', () => {
testFormatLine('from..x import', 'from ..x import');
});
test('Raw strings', () => {
testFormatMultiline('z=r""', 0, 'z = r""');
testFormatMultiline('z=rf""', 0, 'z = rf""');
testFormatMultiline('z=R""', 0, 'z = R""');
testFormatMultiline('z=RF""', 0, 'z = RF""');
});
test('Binary @', () => {
testFormatLine('a@ b', 'a @ b');
});
test('Unary operators', () => {
testFormatMultiline('x= - y', 0, 'x = -y');
testFormatMultiline('x= + y', 0, 'x = +y');
testFormatMultiline('x= ~ y', 0, 'x = ~y');
testFormatMultiline('x=-1', 0, 'x = -1');
testFormatMultiline('x= +1', 0, 'x = +1');
testFormatMultiline('x= ~1 ', 0, 'x = ~1');
});
test('Equals with type hints', () => {
testFormatMultiline('def foo(x:int=3,x=100.)', 0, 'def foo(x: int = 3, x=100.)');
});
test('Trailing comma', () => {
testFormatLine('a, =[1]', 'a, = [1]');
});
test('if()', () => {
testFormatLine('if(True) :', 'if (True):');
});
test('lambda arguments', () => {
testFormatMultiline(
'l4= lambda x =lambda y =lambda z= 1: z: y(): x()',
0,
'l4 = lambda x=lambda y=lambda z=1: z: y(): x()'
);
});
test('star in multiline arguments', () => {
testFormatMultiline('x = [\n * param1,\n * param2\n]', 1, ' *param1,');
testFormatMultiline('x = [\n * param1,\n * param2\n]', 2, ' *param2');
});
test('arrow operator', () => {
//testFormatMultiline('def f(a, b: 1, e: 3 = 4, f =5, * g: 6, ** k: 11) -> 12: pass', 0, 'def f(a, b: 1, e: 3 = 4, f=5, *g: 6, **k: 11) -> 12: pass');
testFormatMultiline('def f(a, \n ** k: 11) -> 12: pass', 1, ' **k: 11) -> 12: pass');
});
test('Multiline function call', () => {
testFormatMultiline('def foo(x = 1)', 0, 'def foo(x=1)');
testFormatMultiline('def foo(a\n, x = 1)', 1, ', x=1)');
testFormatMultiline('foo(a ,b,\n x = 1)', 1, ' x=1)');
testFormatMultiline('if True:\n if False:\n foo(a , bar(\n x = 1)', 3, ' x=1)');
testFormatMultiline('z=foo (0 , x= 1, (3+7) , y , z )', 0, 'z = foo(0, x=1, (3 + 7), y, z)');
testFormatMultiline('foo (0,\n x= 1,', 1, ' x=1,');
testFormatMultiline(
// tslint:disable-next-line:no-multiline-string
`async def fetch():
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
"http://127.0.0.1:8000/", headers = cookie) as ws: # add unwanted spaces`,
3,
' "http://127.0.0.1:8000/", headers=cookie) as ws: # add unwanted spaces'
);
testFormatMultiline('def pos0key1(*, key): return key\npos0key1(key= 100)', 1, 'pos0key1(key=100)');
testFormatMultiline(
'def test_string_literals(self):\n x= 1; y =2; self.assertTrue(len(x) == 0 and x == y)',
1,
' x = 1; y = 2; self.assertTrue(len(x) == 0 and x == y)'
);
});
test('Grammar file', () => {
const content = fs.readFileSync(grammarFile).toString('utf8');
const lines = content.splitLines({ trim: false, removeEmptyEntries: false });
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
const actual = formatMultiline(content, i);
assert.equal(actual, line, `Line ${i + 1} changed: '${line.trim()}' to '${actual.trim()}'`);
}
});
function testFormatLine(text: string, expected: string): void {
const actual = formatLine(text);
assert.equal(actual, expected);
}
function testFormatMultiline(content: string, lineNumber: number, expected: string): void {
const actual = formatMultiline(content, lineNumber);
assert.equal(actual, expected);
}
function formatMultiline(content: string, lineNumber: number): string {
const lines = content.splitLines({ trim: false, removeEmptyEntries: false });
const document = TypeMoq.Mock.ofType<TextDocument>();
document
.setup((x) => x.lineAt(TypeMoq.It.isAnyNumber()))
.returns((n) => {
const line = TypeMoq.Mock.ofType<TextLine>();
line.setup((x) => x.text).returns(() => lines[n]);
line.setup((x) => x.range).returns(
() => new Range(new Position(n, 0), new Position(n, lines[n].length))
);
return line.object;
});
document
.setup((x) => x.getText(TypeMoq.It.isAny()))
.returns((o) => {
const r = o as Range;
const bits: string[] = [];
if (r.start.line === r.end.line) {
return lines[r.start.line].substring(r.start.character, r.end.character);
}
bits.push(lines[r.start.line].substr(r.start.character));
for (let i = r.start.line + 1; i < r.end.line; i += 1) {
bits.push(lines[i]);
}
bits.push(lines[r.end.line].substring(0, r.end.character));
return bits.join('\n');
});
document
.setup((x) => x.offsetAt(TypeMoq.It.isAny()))
.returns((o) => {
const p = o as Position;
let offset = 0;
for (let i = 0; i < p.line; i += 1) {
offset += lines[i].length + 1; // Accounting for the line break
}
return offset + p.character;
});
return formatter.formatLine(document.object, lineNumber);
}
function formatLine(text: string): string {
const line = TypeMoq.Mock.ofType<TextLine>();
line.setup((x) => x.text).returns(() => text);
const document = TypeMoq.Mock.ofType<TextDocument>();
document.setup((x) => x.lineAt(TypeMoq.It.isAnyNumber())).returns(() => line.object);
return formatter.formatLine(document.object, 0);
}
});