forked from microsoft/python-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnalysisTest.cs
More file actions
7521 lines (6208 loc) · 260 KB
/
AnalysisTest.cs
File metadata and controls
7521 lines (6208 loc) · 260 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Python.LanguageServer;
using Microsoft.Python.LanguageServer.Implementation;
using Microsoft.Python.UnitTests.Core.MSTest;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Analysis.FluentAssertions;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Ast;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
namespace AnalysisTests {
[TestClass]
public class AnalysisTest {
public TestContext TestContext { get; set; }
[TestInitialize]
public void TestInitialize() {
TestEnvironmentImpl.TestInitialize($"{TestContext.FullyQualifiedTestClassName}.{TestContext.TestName}");
}
[TestCleanup]
public void TestCleanup() {
TestEnvironmentImpl.TestCleanup();
}
#region Test Cases
[TestMethod, Priority(0)]
public void CheckInterpreterV2() {
using (var interp = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7)).CreateInterpreter()) {
try {
interp.GetBuiltinType((BuiltinTypeId)(-1));
Assert.Fail("Expected KeyNotFoundException");
} catch (KeyNotFoundException) {
}
var intType = interp.GetBuiltinType(BuiltinTypeId.Int);
Assert.IsTrue(intType.ToString() != "");
}
}
[TestMethod, Priority(0)]
public void CheckInterpreterV3() {
using (var interp = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 6)).CreateInterpreter()) {
try {
interp.GetBuiltinType((BuiltinTypeId)(-1));
Assert.Fail("Expected KeyNotFoundException");
} catch (KeyNotFoundException) {
}
var intType = interp.GetBuiltinType(BuiltinTypeId.Int);
Assert.IsTrue(intType.ToString() != "");
}
}
[TestMethod, Priority(0)]
public async Task SpecialArgTypes() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var code = @"def f(*fob, **oar):
pass
";
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveFunction("f")
.Which.Should()
.HaveParameter("fob").OfType(BuiltinTypeId.Tuple)
.And.HaveParameter("oar").OfType(BuiltinTypeId.Dict);
code = @"def f(*fob):
pass
f(42)
";
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveFunction("f")
.Which.Should().HaveParameter("fob").OfType(BuiltinTypeId.Tuple).WithValue<SequenceInfo>()
.Which.Should().HaveIndexType(0, BuiltinTypeId.Int);
code = @"def f(*fob):
pass
f(42, 'abc')
";
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveFunction("f")
.Which.Should().HaveParameter("fob").OfType(BuiltinTypeId.Tuple).WithValue<SequenceInfo>()
.Which.Should().HaveIndexTypes(0, BuiltinTypeId.Int, BuiltinTypeId.Str);
code = @"def f(*fob):
pass
f(42, 'abc')
f('abc', 42)
";
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveFunction("f")
.Which.Should().HaveParameter("fob").OfType(BuiltinTypeId.Tuple).WithValue<SequenceInfo>()
.Which.Should().HaveIndexTypes(0, BuiltinTypeId.Int, BuiltinTypeId.Str);
code = @"def f(**oar):
y = oar['fob']
pass
f(x=42)
";
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveFunction("f")
.Which.Should()
.HaveVariable("y").OfResolvedType(BuiltinTypeId.Int)
.And.HaveParameter("oar").OfType(BuiltinTypeId.Dict).WithValue<DictionaryInfo>()
.Which.Should().HaveValueType(BuiltinTypeId.Int);
code = @"def f(**oar):
z = oar['fob']
pass
f(x=42, y = 'abc')
";
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveFunction("f")
.Which.Should()
.HaveVariable("z").OfResolvedTypes(BuiltinTypeId.Int, BuiltinTypeId.Str)
.And.HaveParameter("oar").OfType(BuiltinTypeId.Dict).WithValue<DictionaryInfo>()
.Which.Should().HaveValueTypes(BuiltinTypeId.Int, BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task TestPackageImportStar() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable3X)) {
var fob = await server.AddModuleWithContentAsync("fob", "fob\\__init__.py", "from oar import *");
var oar = await server.AddModuleWithContentAsync("fob.oar", "fob\\oar\\__init__.py", "from .baz import *");
var baz = await server.AddModuleWithContentAsync("fob.oar.baz", "fob\\oar\\baz.py", "import fob.oar.quox as quox\r\nfunc = quox.func");
var quox = await server.AddModuleWithContentAsync("fob.oar.quox", "fob\\oar\\quox.py", "def func(): return 42");
var fobAnalysis = await fob.GetAnalysisAsync();
var oarAnalysis = await oar.GetAnalysisAsync();
var bazAnalysis = await baz.GetAnalysisAsync();
var quoxAnalysis = await quox.GetAnalysisAsync();
fobAnalysis.Should().HaveVariable("func").WithDescription("fob.oar.quox.func() -> int");
oarAnalysis.Should().HaveVariable("func").WithDescription("fob.oar.quox.func() -> int");
bazAnalysis.Should().HaveVariable("func").WithDescription("fob.oar.quox.func() -> int");
quoxAnalysis.Should().HaveVariable("func").WithDescription("fob.oar.quox.func() -> int");
}
}
[TestMethod, Priority(0)]
public async Task TestClassAssignSameName() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var code = @"x = 123
class A:
x = x
pass
class B:
x = 3.1415
x = x
";
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int);
analysis.Should().HaveClass("A")
.Which.Should().HaveVariable("x").OfType(BuiltinTypeId.Int);
// Arguably this should only be float, but since we don't support
// definite assignment having both int and float is correct now.
//
// It also means we handle this case consistently:
//
// class B(object):
// if False:
// x = 3.1415
// x = x
analysis.Should().HaveClass("B")
.Which.Should().HaveVariable("x").OfTypes(BuiltinTypeId.Int, BuiltinTypeId.Float);
}
}
[TestMethod, Priority(0)]
public async Task TestFunctionAssignSameName() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var code = @"x = 123
def f():
x = x
return x
y = f()
";
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfTypes(BuiltinTypeId.Int)
.And.HaveVariable("y").OfTypes(BuiltinTypeId.Int)
.And.HaveFunction("f")
.Which.Should().HaveVariable("x").OfTypes(BuiltinTypeId.Int)
.And.HaveReturnValue().OfTypes(BuiltinTypeId.Int);
}
}
/// <summary>
/// Binary operators should assume their result type
/// https://pytools.codeplex.com/workitem/1575
///
/// Slicing should assume the incoming type
/// https://pytools.codeplex.com/workitem/1581
/// </summary>
[TestMethod, Priority(0)]
public async Task TestBuiltinOperatorsFallback() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var code = @"import array
slice = array.array('b', b'abcdef')[2:3]
add = array.array('b', b'abcdef') + array.array('b', b'fob')
";
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("slice").OfType("array")
.And.HaveVariable("add").OfType("array");
}
}
[TestMethod, Priority(0)]
public async Task ExcessPositionalArguments() {
var code = @"def f(a, *args):
return args[0]
x = f('abc', 1)
y = f(1, 'abc')
z = f(None, 'abc', 1)
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Str)
.And.HaveVariable("z").OfTypes(BuiltinTypeId.Str, BuiltinTypeId.Int);
}
}
[TestMethod, Priority(0)]
public async Task ExcessNamedArguments() {
var code = @"def f(a, **args):
return args[a]
x = f(a='b', b=1)
y = f(a='c', c=1.3)
z = f(a='b', b='abc')
w = f(a='p', p=1, q='abc')
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Float)
.And.HaveVariable("z").OfTypes(BuiltinTypeId.Str)
.And.HaveVariable("w").OfTypes(BuiltinTypeId.Str, BuiltinTypeId.Int);
}
}
[TestMethod, Priority(0), Timeout(5000)]
public async Task RecursiveListComprehensionV32() {
var code = @"
def f(x):
x = []
x = [i for i in x]
x = (i for i in x)
f(x)
";
// If we complete processing then we have succeeded
using (var server = await CreateServerAsync(PythonVersions.Required_Python32X)) {
await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
}
}
//[TestMethod, Priority(2)]
//[TestCategory("ExpectFail")]
public async Task CartesianStarArgs() {
// TODO: Figure out whether this is useful behaviour
// It currently does not work because we no longer treat
// the dict created by **args as a lasting object - it
// exists solely for receiving arguments.
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var code = @"def f(a, **args):
args['fob'] = a
return args['fob']
x = f(42)
y = f('abc')";
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Str);
code = @"def f(a, **args):
for i in xrange(2):
if i == 1:
return args['fob']
else:
args['fob'] = a
x = f(42)
y = f('abc')";
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task CartesianRecursive() {
var code = @"def f(a, *args):
f(a, args)
return a
x = f(42)";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int);
}
}
[TestMethod, Priority(0)]
public async Task CartesianSimple() {
var code = @"def f(a):
return a
x = f(42)
y = f('fob')";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task CartesianLocals() {
var code = @"def f(a):
b = a
return b
x = f(42)
y = f('fob')";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task CartesianClosures() {
var code = @"def f(a):
def g():
return a
return g()
x = f(42)
y = f('fob')";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task CartesianContainerFactory() {
var code = @"def list_fact(ctor):
x = []
for abc in xrange(10):
x.append(ctor(abc))
return x
a = list_fact(int)[0]
b = list_fact(str)[0]
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("a").OfType(BuiltinTypeId.Int)
.And.HaveVariable("b").OfType(BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task CartesianLocalsIsInstance() {
var code = @"def f(a, c):
if isinstance(c, int):
b = a
return b
else:
b = a
return b
x = f(42, 'oar')
y = f('fob', 'oar')";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfType(BuiltinTypeId.Str);
}
}
// [TestMethod, Priority(0)]
// public void CartesianMerge() {
// var limits = GetLimits();
// // Ensure we include enough calls
// var callCount = limits.CallDepth * limits.DecreaseCallDepth + 1;
// var code = new StringBuilder(@"def f(a):
// return g(a)
//def g(b):
// return h(b)
//def h(c):
// return c
//");
// for (int i = 0; i < callCount; ++i) {
// code.AppendLine("x = g(123)");
// }
// code.AppendLine("y = f(3.1415)");
// var text = code.ToString();
// Console.WriteLine(text);
// var entry = ProcessTextV2(text);
// entry.AssertIsInstance("x", BuiltinTypeId.Int, BuiltinTypeId.Float);
// entry.AssertIsInstance("y", BuiltinTypeId.Int, BuiltinTypeId.Float);
// }
[TestMethod, Priority(0)]
public async Task ImportAs() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable3X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(@"import sys as s, array as a");
analysis.Should().HavePythonModuleVariable("s")
.Which.Should().HaveMember<AstPythonStringLiteral>("winver");
analysis.Should().HavePythonModuleVariable("a")
.Which.Should().HaveMember<AstPythonConstant>("ArrayType");
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(@"import sys as s");
analysis.Should().HavePythonModuleVariable("s")
.Which.Should().HaveMember<AstPythonStringLiteral>("winver");
}
}
[TestMethod, Priority(0)]
public async Task DictionaryKeyValues() {
var code = @"x = {'abc': 42, 'oar': 'baz'}
i = x['abc']
s = x['oar']
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("i").OfType(BuiltinTypeId.Int)
.And.HaveVariable("s").OfType(BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task RecursiveLists() {
var code = @"x = []
x.append(x)
y = []
y.append(y)
def f(a):
return a[0]
x2 = f(x)
y2 = f(y)
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x").OfType(BuiltinTypeId.List)
.And.HaveVariable("y").OfType(BuiltinTypeId.List)
.And.HaveVariable("x2").OfType(BuiltinTypeId.List)
.And.HaveVariable("y2").OfType(BuiltinTypeId.List);
}
}
[TestMethod, Priority(0)]
public async Task RecursiveDictionaryKeyValues() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var uri = TestData.GetTempPathUri("test-module.py");
var code = @"x = {'abc': 42, 'oar': 'baz'}
x['abc'] = x
x[x] = 'abc'
i = x['abc']
s = x['abc']['abc']['abc']['oar']
t = x[x]
";
await server.SendDidOpenTextDocument(uri, code);
var analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveVariable("i").OfTypes(BuiltinTypeId.Int, BuiltinTypeId.Dict)
.And.HaveVariable("s").OfType(BuiltinTypeId.Str)
.And.HaveVariable("t").OfType(BuiltinTypeId.Str);
code = @"x = {'y': None, 'value': 123 }
y = { 'x': x, 'value': 'abc' }
x['y'] = y
i = x['y']['x']['value']
s = y['x']['y']['value']
";
await server.SendDidChangeTextDocumentAsync(uri, code);
analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveVariable("i").OfTypes(BuiltinTypeId.Int)
.And.HaveVariable("s").OfType(BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
[Ignore("https://github.com/Microsoft/python-language-server/issues/50")]
public async Task RecursiveTuples() {
var code = @"class A(object):
def __init__(self):
self.top = None
def fn(self, x, y):
top = self.top
if x > y:
self.fn(y, x)
return
self.top = x, y, top
def pop(self):
self.top = self.top[2]
def original(self, item=None):
if item == None:
item = self.top
if item[2] != None:
self.original(item[2])
x, y, _ = item
a=A()
a.fn(1, 2)
a.fn(3, 4)
a.fn(5, 6)
a.fn(7, 8)
a.fn(9, 10)
a.fn(11, 12)
a.fn(13, 14)
x1, y1, _1 = a.top
a.original()
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("x1").OfResolvedType(BuiltinTypeId.Int)
.And.HaveVariable("y1").OfResolvedType(BuiltinTypeId.Int)
.And.HaveVariable("_1").OfResolvedTypes(BuiltinTypeId.Tuple, BuiltinTypeId.NoneType)
.And.HaveClass("A").WithFunction("original")
.Which.Should().HaveVariable("item").OfResolvedTypes(BuiltinTypeId.Tuple, BuiltinTypeId.NoneType)
.And.HaveVariable("x").OfResolvedType(BuiltinTypeId.Int)
.And.HaveVariable("y").OfResolvedType(BuiltinTypeId.Int)
.And.HaveVariable("_").OfResolvedTypes(BuiltinTypeId.Tuple, BuiltinTypeId.NoneType)
.And.HaveParameter("self").WithValue<IInstanceInfo>()
.Which.Should().HaveMemberOfTypes("top", BuiltinTypeId.Tuple, BuiltinTypeId.NoneType);
}
}
[TestMethod, Priority(0)]
public async Task RecursiveSequences() {
var code = @"
x = []
x.append(x)
x.append(1)
x.append(3.14)
x.append('abc')
x.append(x)
y = x[0]
";
// Completing analysis is the main test, but we'll also ensure that
// the right types are in the list.
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveVariable("y").OfTypes(BuiltinTypeId.List, BuiltinTypeId.Int, BuiltinTypeId.Float, BuiltinTypeId.Str);
}
}
[TestMethod, Priority(0)]
public async Task CombinedTupleSignatures() {
var code = @"def a():
if x:
return (1, True)
elif y:
return (1, True)
else:
return (2, False)
x = a()
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveFunction("a")
.Which.Should().HaveReturnValue().OfType(BuiltinTypeId.Tuple);
}
}
[TestMethod, Priority(0)]
public async Task ImportStar() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(@"
from nt import *
");
analysis.Should().HaveVariable("abort");
// make sure abort hasn't become a builtin, if so this test needs to be updated
// with a new name
analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(@"");
analysis.Should().NotHaveVariable("abort");
}
}
[TestMethod, Priority(0)]
public async Task ImportTrailingComma() {
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(@"
import nt,
");
analysis.Should().HavePythonModuleVariable("nt")
.Which.Should().HaveMembers("abort");
}
}
[TestMethod, Priority(0)]
public async Task ImportStarCorrectRefs() {
var text1 = @"
from mod2 import *
a = D()
";
var text2 = @"
class D(object):
pass
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable3X)) {
var uri1 = TestData.GetTempPathUri("mod1.py");
var uri2 = TestData.GetTempPathUri("mod2.py");
await server.SendDidOpenTextDocument(uri1, text1);
await server.SendDidOpenTextDocument(uri2, text2);
var references = await server.SendFindReferences(uri2, 1, 7);
references.Should().OnlyHaveReferences(
(uri1, (3, 4, 3, 5), ReferenceKind.Reference),
(uri2, (1, 0, 2, 8), ReferenceKind.Value),
(uri2, (1, 6, 1, 7), ReferenceKind.Definition)
);
}
}
[TestMethod, Priority(0)]
[Ignore("https://github.com/Microsoft/python-language-server/issues/47")]
public async Task MutatingReferences() {
var text1 = @"
import mod2
class C(object):
def SomeMethod(self):
pass
mod2.D(C())
";
var text2 = @"
class D(object):
def __init__(self, value):
self.value = value
self.value.SomeMethod()
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable3X)) {
var uri1 = TestData.GetNextModuleUri();
var uri2 = TestData.GetNextModuleUri();
await server.SendDidOpenTextDocument(uri1, text1);
await server.SendDidOpenTextDocument(uri2, text2);
var references = await server.SendFindReferences(uri1, 4, 9);
references.Should().OnlyHaveReferences(
(uri1, (4, 4, 5, 12), ReferenceKind.Value),
(uri1, (4, 8, 4, 18), ReferenceKind.Definition),
(uri2, (4, 19, 4, 29), ReferenceKind.Reference)
);
text1 = text1.Substring(0, text1.IndexOf(" def")) + Environment.NewLine + text1.Substring(text1.IndexOf(" def"));
await server.SendDidChangeTextDocumentAsync(uri1, text1);
references = await server.SendFindReferences(uri1, 5, 9);
references.Should().OnlyHaveReferences(
(uri1, (5, 4, 6, 12), ReferenceKind.Value),
(uri1, (5, 8, 5, 18), ReferenceKind.Definition),
(uri2, (4, 19, 4, 29), ReferenceKind.Reference)
);
text2 = Environment.NewLine + text2;
await server.SendDidChangeTextDocumentAsync(uri2, text2);
references = await server.SendFindReferences(uri1, 5, 9);
references.Should().OnlyHaveReferences(
(uri1, (5, 4, 6, 12), ReferenceKind.Value),
(uri1, (5, 8, 5, 18), ReferenceKind.Definition),
(uri2, (5, 19, 5, 29), ReferenceKind.Reference)
);
}
}
[TestMethod, Priority(0)]
[Ignore("https://github.com/Microsoft/python-language-server/issues/46")]
public async Task MutatingCalls() {
var text1 = @"
def f(abc):
return abc
";
var text2 = @"
import mod1
z = mod1.f(42)
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable3X)) {
var uri1 = TestData.GetTempPathUri("mod1.py");
var uri2 = TestData.GetTempPathUri("mod2.py");
await server.SendDidOpenTextDocument(uri1, text1);
await server.SendDidOpenTextDocument(uri2, text2);
var analysis1 = await server.GetAnalysisAsync(uri1);
var analysis2 = await server.GetAnalysisAsync(uri2);
analysis1.Should().HaveFunction("f")
.Which.Should().HaveParameter("abc").OfType(BuiltinTypeId.Int);
analysis2.Should().HaveVariable("z").OfType(BuiltinTypeId.Int);
//change caller in text2
text2 = @"
import mod1
z = mod1.f('abc')
";
await server.SendDidChangeTextDocumentAsync(uri2, text2);
analysis2 = await server.GetAnalysisAsync(uri2);
analysis1.Should().HaveFunction("f")
.Which.Should().HaveParameter("abc").OfType(BuiltinTypeId.Str);
analysis2.Should().HaveVariable("z").OfType(BuiltinTypeId.Str);
}
}
/* Doesn't pass, we don't have a way to clear the assignments across modules...
[TestMethod, Priority(0)]
public void MutatingVariables() {
using (var state = PythonAnalyzer.CreateSynchronously(InterpreterFactory, Interpreter)) {
var text1 = @"
print(x)
";
var text2 = @"
import mod1
mod1.x = x
";
var text3 = @"
import mod2
mod2.x = 42
";
var mod1 = state.AddModule("mod1", "mod1", null);
Prepare(mod1, GetSourceUnit(text1, "mod1"));
var mod2 = state.AddModule("mod2", "mod2", null);
Prepare(mod2, GetSourceUnit(text2, "mod2"));
var mod3 = state.AddModule("mod3", "mod3", null);
Prepare(mod3, GetSourceUnit(text3, "mod3"));
mod3.Analyze(CancellationToken.None);
mod2.Analyze(CancellationToken.None);
mod1.Analyze(CancellationToken.None);
state.AnalyzeQueuedEntries(CancellationToken.None);
AssertUtil.ContainsExactly(
mod1.Analysis.GetDescriptionsByIndex("x", text1.IndexOf("x")),
"int"
);
text3 = @"
import mod2
mod2.x = 'abc'
";
Prepare(mod3, GetSourceUnit(text3, "mod3"));
mod3.Analyze(CancellationToken.None);
state.AnalyzeQueuedEntries(CancellationToken.None);
state.AnalyzeQueuedEntries(CancellationToken.None);
AssertUtil.ContainsExactly(
mod1.Analysis.GetDescriptionsByIndex("x", text1.IndexOf("x")),
"str"
);
}
}
*/
[TestMethod, Priority(0)]
public async Task BaseInstanceVariable() {
var code = @"
class C:
def __init__(self):
self.abc = 42
class D(C):
def __init__(self):
self.fob = self.abc
";
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code);
analysis.Should().HaveClass("D").WithFunction("__init__")
.Which.Should().HaveParameter("self").WithValue<IInstanceInfo>()
.Which.Should().HaveMemberOfType("fob", BuiltinTypeId.Int)
.And.HaveMemberOfType("abc", BuiltinTypeId.Int);
}
}
[TestMethod, Priority(0)]
public async Task Mro() {
var uri = TestData.GetTempPathUri("test-module.py");
string code;
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable2X)) {
// Successful: MRO is A B C D E F object
code = @"
O = object
class F(O): pass
class E(O): pass
class D(O): pass
class C(D,F): pass
class B(D,E): pass
class A(B,C): pass
a = A()
";
await server.SendDidOpenTextDocument(uri, code);
var analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveClassInfo("A")
.WithMethodResolutionOrder("A", "B", "C", "D", "E", "F", "type object");
// Unsuccessful: cannot order X and Y
code = @"
O = object
class X(O): pass
class Y(O): pass
class A(X, Y): pass
class B(Y, X): pass
class C(A, B): pass
c = C()
";
await server.SendDidChangeTextDocumentAsync(uri, code);
analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveClassInfo("C")
.Which.Should().HaveInvalidMethodResolutionOrder();
// Unsuccessful: cannot order F and E
code = @"
class F(object): remember2buy='spam'
class E(F): remember2buy='eggs'
class G(F,E): pass
G.remember2buy
";
await server.SendDidChangeTextDocumentAsync(uri, code);
analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveClassInfo("G")
.Which.Should().HaveInvalidMethodResolutionOrder();
// Successful: exchanging bases of G fixes the ordering issue
code = @"
class F(object): remember2buy='spam'
class E(F): remember2buy='eggs'
class G(E,F): pass
G.remember2buy
";
await server.SendDidChangeTextDocumentAsync(uri, code);
analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveClassInfo("G")
.WithMethodResolutionOrder("G", "E", "F", "type object");
// Successful: MRO is Z K1 K2 K3 D A B C E object
code = @"
class A(object): pass
class B(object): pass
class C(object): pass
class D(object): pass
class E(object): pass
class K1(A,B,C): pass
class K2(D,B,E): pass
class K3(D,A): pass
class Z(K1,K2,K3): pass
z = Z()
";
await server.SendDidChangeTextDocumentAsync(uri, code);
analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveClassInfo("Z")
.WithMethodResolutionOrder("Z", "K1", "K2", "K3", "D", "A", "B", "C", "E", "type object");
// Successful: MRO is Z K1 K2 K3 D A B C E object
code = @"
class A(int): pass
class B(float): pass
class C(str): pass
z = None
";
await server.SendDidChangeTextDocumentAsync(uri, code);
analysis = await server.GetAnalysisAsync(uri);
analysis.Should().HaveClassInfo("A").WithMethodResolutionOrder("A", "type int", "type object")
.And.HaveClassInfo("B").WithMethodResolutionOrder("B", "type float", "type object")
.And.HaveClassInfo("C").WithMethodResolutionOrder("C", "type str", "type basestring", "type object");
}
using (var server = await CreateServerAsync(PythonVersions.LatestAvailable3X)) {
await server.SendDidOpenTextDocument(uri, code);
var analysis = await server.GetAnalysisAsync(uri);