forked from microsoft/python-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen.py
More file actions
362 lines (288 loc) · 10.1 KB
/
gen.py
File metadata and controls
362 lines (288 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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#!/usr/bin/env python
import argparse
import contextlib
from collections import defaultdict
import string
import sys
import os.path
def main():
script_path = os.path.realpath(__file__)
script_dir = os.path.dirname(script_path)
default_input = os.path.join(
script_dir, "UnitTests", "TestData", "gen", "completion"
)
default_output = os.path.join(
script_dir, "Analysis", "Engine", "Test", "GenTests.cs"
)
parser = argparse.ArgumentParser(
description="Generate completion and hover tests",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--ignore",
type=str,
help="comma separated list of tests to disable, of the form <filename>(:<linenum>)",
)
parser.add_argument(
"--only", type=str, help="comma separated list of tests to generate"
)
parser.add_argument(
"-o",
"--out",
nargs="?",
type=argparse.FileType("w"),
default=default_output,
help="output file",
)
parser.add_argument(
"-i",
"--input",
type=str,
default=default_input,
help="location of completions directory",
)
args = parser.parse_args()
if args.only:
to_generate = set(args.only.split(","))
else:
to_generate = set(DEFAULT_TEST_FILES)
line_skip = defaultdict(set)
if args.ignore:
for i in args.ignore.split(","):
if ":" not in i:
to_generate.discard(i)
else:
name, line = i.split(":")
try:
line = int(line)
except:
print(f"error in format of ignored item {i}", file=sys.stderr)
return
line_skip[name].add(line)
to_generate = sorted(to_generate)
with contextlib.redirect_stdout(args.out):
print(PREAMBLE)
for name in to_generate:
filename = os.path.join(args.input, name + ".py")
ignored_lines = line_skip[name]
create_tests(name, filename, ignored_lines)
print(POSTAMBLE)
def create_tests(name, filename, ignored_lines):
camel_name = snake_to_camel(name)
with open(filename) as fp:
lines = fp.read().splitlines()
width = len(str(len(lines)))
tests = []
for i, line in enumerate(lines):
if i in ignored_lines:
continue
line: str = line.strip()
if not line.startswith("#?"):
continue
line = line[2:].strip()
next_line = lines[i + 1]
col = len(next_line)
if " " in line:
maybe_num = line.split(" ", 1)
try:
col = int(maybe_num[0])
line = maybe_num[1]
except ValueError:
pass
filt = next_line[:col].lstrip()
filt = select_filter(filt, ". {[(")
args = line.strip()
func_name = "Line_{0:0{pad}}".format(i + 1, pad=width)
func_name = camel_name + "_" + func_name
tmpl = COMPLETION_TEST if args.startswith("[") else HOVER_TEST
tests.append(
tmpl.format(
name=func_name,
module=csharp_str(name),
line=i + 1,
col=col,
args=csharp_str(args),
filter=csharp_str(filt),
)
)
if tests:
print(CLASS_PREAMBLE.format(name=camel_name))
for t in tests:
print(t)
print(CLASS_POSTAMBLE)
DEFAULT_TEST_FILES = [
"arrays",
"async_",
"basic",
"classes",
"completion",
"complex",
"comprehensions",
"context",
"decorators",
"definition",
"descriptors",
"docstring",
"dynamic_arrays",
"dynamic_params",
"flow_analysis",
"fstring",
"functions",
"generators",
"imports",
"invalid",
"isinstance",
"keywords",
"lambdas",
"named_param",
"on_import",
"ordering",
"parser",
"pep0484_basic",
"pep0484_comments",
"pep0484_typing",
"pep0526_variables",
"precedence",
"recursion",
"stdlib",
"sys_path",
"types",
]
PREAMBLE = """// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AnalysisTests;
using FluentAssertions;
using Microsoft.Python.LanguageServer.Implementation;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Analysis.FluentAssertions;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
namespace GenTests {"""
POSTAMBLE = """
public class GenTest : ServerBasedTest {
private static Server _server;
private static readonly SemaphoreSlim _sem = new SemaphoreSlim(1, 1);
private static readonly InterpreterConfiguration _interpreter = PythonVersions.LatestAvailable3X;
private static readonly PythonLanguageVersion _version = _interpreter.Version.ToLanguageVersion();
private static readonly ConcurrentDictionary<string, Task> _opened = new ConcurrentDictionary<string, Task>();
private async Task<Server> SharedServer() {
if (_server != null) {
return _server;
}
await _sem.WaitAsync();
try {
var root = new Uri(TestData.GetPath("TestData", "gen", "completion"));
_server = await CreateServerAsync(_interpreter, root);
} finally {
_sem.Release();
}
return _server;
}
protected async Task<Uri> OpenAndWait(string module) {
var server = await SharedServer();
var src = TestData.GetPath("TestData", "gen", "completion", module + ".py");
var uri = new Uri(src);
await _opened.GetOrAdd(src, f => server.SendDidOpenTextDocument(uri, File.ReadAllText(f)));
await server.WaitForCompleteAnalysisAsync(CancellationToken.None);
return uri;
}
protected async Task DoCompletionTest(string module, int lineNum, int col, string args, string filter) {
var server = await SharedServer();
var tests = string.IsNullOrWhiteSpace(args) ? new List<string>() : ParseStringList(args);
var uri = await OpenAndWait(module);
var res = await server.SendCompletion(uri, lineNum, col);
var items = res.items?.Select(item => item.insertText).Where(t => t.Contains(filter)).ToList() ?? new List<string>();
if (tests.Count == 0) {
items.Should().BeEmpty();
} else {
items.Should().Contain(tests);
}
}
protected async Task DoHoverTest(string module, int lineNum, int col, string args) {
var server = await SharedServer();
var tests = string.IsNullOrWhiteSpace(args)
? new List<string>()
: args.Split(' ', options: StringSplitOptions.RemoveEmptyEntries).Select(s => s.EndsWith("()") ? s.Substring(0, s.Length - 2) : s).ToList();
var uri = await OpenAndWait(module);
var res = await server.SendHover(uri, lineNum, col);
if (tests.Count == 0) {
res.contents.value.Should().BeEmpty();
} else {
res.contents.value.Should().ContainAll(tests);
}
}
protected List<string> ParseStringList(string s) {
var list = new List<string>();
using (var reader = new StringReader(s)) {
var tokenizer = new Tokenizer(_version);
tokenizer.Initialize(reader);
while (!tokenizer.IsEndOfFile) {
var token = tokenizer.GetNextToken();
if (token.Kind == TokenKind.EndOfFile) {
break;
}
switch (token.Kind) {
case TokenKind.Constant when token != Tokens.NoneToken && (token.Value is string || token.Value is AsciiString):
list.Add(token.Image);
break;
}
}
}
return list;
}
}
}"""
CLASS_PREAMBLE = """ [TestClass]
public class {name}Tests : GenTest {{
public TestContext TestContext {{ get; set; }}
[TestInitialize]
public void TestInitialize() => TestEnvironmentImpl.TestInitialize($"{{TestContext.FullyQualifiedTestClassName}}.{{TestContext.TestName}}");
[TestCleanup]
public void TestCleanup() => TestEnvironmentImpl.TestCleanup();"""
CLASS_POSTAMBLE = """
}"""
COMPLETION_TEST = """
[TestMethod, Priority(0)] public async Task {name}_Completion() => await DoCompletionTest({module}, {line}, {col}, {args}, {filter});"""
HOVER_TEST = """
[TestMethod, Priority(0)] public async Task {name}_Hover() => await DoHoverTest({module}, {line}, {col}, {args});"""
def snake_to_camel(s):
return string.capwords(s, "_").replace("_", "")
def select_filter(s, cs):
found = False
for c in cs:
i = s.rfind(c)
if i != -1:
found = True
s = s[i + 1 :]
if found:
return s
return ""
def csharp_str(s):
if s is None:
return "null"
s = s.replace('"', '""')
return '@"{}"'.format(s)
if __name__ == "__main__":
main()