This repository was archived by the owner on Apr 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathLintUndefinedVarsTests.cs
More file actions
862 lines (751 loc) · 21.5 KB
/
LintUndefinedVarsTests.cs
File metadata and controls
862 lines (751 loc) · 21.5 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
// 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.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Python.Analysis.Analyzer;
using Microsoft.Python.Analysis.Core.Interpreter;
using Microsoft.Python.Analysis.Diagnostics;
using Microsoft.Python.Analysis.Tests.FluentAssertions;
using Microsoft.Python.Parsing.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using ErrorCodes = Microsoft.Python.Analysis.Diagnostics.ErrorCodes;
namespace Microsoft.Python.Analysis.Tests {
[TestClass]
public class LintUndefinedVarsTests : AnalysisTestBase {
public TestContext TestContext { get; set; }
[TestInitialize]
public void TestInitialize()
=> TestEnvironmentImpl.TestInitialize($"{TestContext.FullyQualifiedTestClassName}.{TestContext.TestName}");
[TestCleanup]
public void Cleanup() => TestEnvironmentImpl.TestCleanup();
[TestMethod, Priority(0)]
public async Task BasicVariables() {
const string code = @"
y = x
class A:
x1: int = 0
y1: int
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(2, 5, 2, 6);
}
[TestMethod, Priority(0)]
public async Task ClassVariables() {
const string code = @"
class A:
x1: int = 0
y1: int
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task Conditionals() {
const string code = @"
z = 3
if x > 2 and y == 3 or z < 2:
pass
";
var d = await LintAsync(code);
d.Should().HaveCount(2);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(3, 4, 3, 5);
d[1].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[1].SourceSpan.Should().Be(3, 14, 3, 15);
}
[TestMethod, Priority(0)]
public async Task Calls() {
const string code = @"
z = 3
func(x, 1, y+1, z)
";
var d = await LintAsync(code);
d.Should().HaveCount(3);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(3, 1, 3, 5);
d[1].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[1].SourceSpan.Should().Be(3, 6, 3, 7);
d[2].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[2].SourceSpan.Should().Be(3, 12, 3, 13);
}
[TestMethod, Priority(0)]
public async Task TupleAssignment() {
const string code = @"
a, *b, c = range(5)
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task TupleUsage() {
const string code = @"
a, b = 1
x = a
y = b
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task FunctionNoneArgument() {
const string code = @"
def func(a=None, b=True):
x = a
y = b
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task FunctionReference() {
const string code = @"
def func1():
func2()
return
def func2(a=None, b=True): ...
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ClassReference() {
const string code = @"
class A(B):
def __init__(self):
x = B()
return
class B(): ...
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ForVariables() {
const string code = @"
c = {}
for i in c:
x = i
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ForVariablesCondition() {
const string code = @"
c = {}
for a, b in c if a < 0:
x = b
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ForVariablesList() {
const string code = @"
for i, (j, k) in {}:
x = j
y = k
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ForExpression() {
const string code = @"
def func1(a):
return a
def func2(a, b):
return a + b
func1(func2(a) for a, b in {} if a < 0)
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ListComprehension() {
const string code = @"
NAME = ' '.join(str(x) for x in {z, 2, 3})
class C:
EVENTS = ['x']
x = [(e, e) for e in EVENTS]
y = EVENTS
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(2, 34, 2, 35);
}
[TestMethod, Priority(0)]
public async Task SelfAssignment() {
const string code = @"
def foo(m):
m = m
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task AssignmentBefore() {
const string code = @"
x = 1
y = x
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task AssignmentBeforeAndAfter() {
const string code = @"
x = 1
y = x
x = 's'
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task AssignmentAfter() {
const string code = @"
y = x
x = 1
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(2, 5, 2, 6);
}
[TestMethod, Priority(0)]
public async Task FunctionArguments() {
const string code = @"
def z(x):
return x
def func(a, b, c):
a = b
x = c
z(c * 3)
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task NonLocal() {
const string code = @"
class A:
x: int
def func():
nonlocal x, y
y = 2
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.VariableNotDefinedNonLocal);
d[0].SourceSpan.Should().Be(5, 21, 5, 22);
}
[TestMethod, Priority(0)]
public async Task Global() {
const string code = @"
x = 1
class A:
def func():
global x, y
y = 2
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.VariableNotDefinedGlobally);
d[0].SourceSpan.Should().Be(6, 19, 6, 20);
}
[DataRow(false)]
[DataRow(true)]
[DataTestMethod, Priority(0)]
public async Task OptionsSwitch(bool enabled) {
const string code = @"x = y";
var sm = CreateServiceManager();
var op = new AnalysisOptionsProvider();
sm.AddService(op);
op.Options.LintingEnabled = enabled;
var analysis = await GetAnalysisAsync(code, PythonVersions.LatestAvailable3X, sm);
var a = Services.GetService<IPythonAnalyzer>();
var d = a.LintModule(analysis.Document);
d.Should().HaveCount(enabled ? 1 : 0);
}
[TestMethod, Priority(0)]
public async Task Builtins() {
const string code = @"
print(1)
abs(3)
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task Enumeration() {
const string code = @"
x = {}
for a, b in enumerate(x):
if a:
pass
if b:
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ReassignInLoop() {
const string code = @"
x = {}
for a, b in enumerate(x):
y = a
a = b
b = 1
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ListComprehensionStatement() {
const string code = @"
[a == 1 for a in {}]
x = a
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task DictionaryComprehension() {
const string code = @"
b = {str(a): a == 1 for a in {}}
x = a
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(3, 5, 3, 6);
}
[TestMethod, Priority(0)]
public async Task Lambda() {
const string code = @"
x = lambda a: a
x(1)
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task BuiltinModuleVariables() {
const string code = @"
x1 = __doc__
x2 = __file__
x3 = __name__
x4 = __package__
x5 = __path__
x6 = __dict__
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task BuiltinFunctionVariables() {
const string code = @"
def func():
x1 = __closure__
x2 = __code__
x3 = __defaults__
x4 = __dict__
x5 = __doc__
x6 = __func__
x7 = __name__
x8 = __globals__
x9 = __name__
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task BuiltinClassVariables() {
const string code = @"
class A:
a = __self__
def func():
x1 = __closure__
x2 = __code__
x3 = __defaults__
x4 = __dict__
x5 = __doc__
x6 = __func__
x7 = __name__
x8 = __globals__
x9 = __name__
x10 = __self__
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task LambdaComprehension() {
const string code = @"
y = lambda x: [e for e in x if e == 1]
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task FromFuture() {
const string code = @"
from __future__ import print_function
print()
";
var d = await LintAsync(code, PythonVersions.LatestAvailable2X);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task WithOpenOverUnknown() {
const string code = @"
import xml.etree.ElementTree as ElementTree
class XXX:
def __init__(self, path):
self.path = path
with (self.path / 'object.xml').open() as f:
self.root = ElementTree.parse(f)
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task Various() {
const string code = @"
print x
assert x
del x
";
var d = await LintAsync(code, PythonVersions.LatestAvailable2X);
d.Should().HaveCount(3);
}
[TestMethod, Priority(0)]
public async Task FString() {
const string code = @"
print(f'Hello, {name}. You are {age}.')
";
var d = await LintAsync(code, PythonVersions.LatestAvailable3X);
d.Should().HaveCount(2);
}
[TestMethod, Priority(0)]
public async Task ClassMemberAssignment() {
const string code = @"
class A:
x: int
a = A()
a.x = 1
a.y = 2
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ListAssignment() {
const string code = @"
from datetime import date
[year, month] = date.split(' - ')";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task NoRightSideCheck() {
const string code = @"
x =
y = ";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ListComprehensionFunction() {
const string code = @"
def func_a(value):
return value
def func_b():
list_a = [1, 2, 3, 4]
return [func_a(value=elem) for elem in list_a]
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task NoLeakFromComprehension() {
const string code = @"
len([1 for e in [1, 2]]) + len([e])
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(2, 33, 2, 34);
}
[TestMethod, Priority(0)]
public async Task NestedDictComprehension() {
const string code = @"
dmap = {}
sizes = {}
x = {srv:sum([sizes[d] for d in dbs]) for srv, dbs in dmap.items()}
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task FunctionInIf() {
const string code = @"
def foo(a, b, c):
return a + b + c
if True:
def bar(x, y, z):
x += y
return x + y + z
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task DifferentScopes() {
const string code = @"
def func():
var = _CONSTANT
_CONSTANT = 1
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task GlobalScope() {
const string code = @"
var = _CONSTANT
_CONSTANT = 1
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(2, 7, 2, 16);
}
[TestMethod, Priority(0)]
public async Task ClassMemberDefinition() {
const string code = @"
class A:
i: int
i = 0
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task ForElse() {
const string code = @"
def py_repro():
for n in range(10):
print(n)
else:
error_code = 10
raise NotImplementedError(f'some error: { error_code}')
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task SpecNotUndefined() {
const string code = "__spec__";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task WithAsTuple() {
const string code = @"
class Test:
def __enter__(self) -> Tuple[int, int]:
return (1, 2)
def __exit__(x, y, z, w):
pass
with Test() as (hi, hello):
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task WithAsTupleEnterReturnTypeMismatch() {
const string code = @"
from typing import Tuple
class Test:
def __enter__(self) -> str:
return (1, 2)
def __exit__(x, y, z, w):
pass
with Test() as (test, test1):
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task WithAsTupleEnterNoReturnType() {
const string code = @"
from typing import Tuple
class Test:
def __enter__(self):
return (1, 2)
def __exit__(x, y, z, w):
pass
with Test() as (test, test1):
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task WithList() {
const string code = @"
from typing import List
class Test:
def __enter__(self) -> List[int]:
return [1, 2]
def __exit__(x, y, z, w):
pass
with Test() as [hi, hello]:
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task WithSingleElementTuple() {
const string code = @"
from typing import List
class Test:
def __enter__(self) -> int:
return [1, 2]
def __exit__(x, y, z, w):
pass
with Test() as (a):
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task WithSingleElementList() {
const string code = @"
from typing import List
class Test:
def __enter__(self) -> int:
return [1, 2]
def __exit__(x, y, z, w):
pass
with Test() as [a]:
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task NamedExpr() {
const string code = @"
x = 123
if (y := x):
print(y)
";
var d = await LintAsync(code, PythonVersions.Required_Python38X);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task NamedExprInComprehension() {
// This code is syntactically incorrect due to the intruction of a name in the iterable expression,
// but since we still recover, ensure that no warnings are reported in addition to the sytnax errors.
const string code = @"
stuff = []
[i+1 for i in range(2) for j in (k := stuff)]
[i+1 for i in [j for j in (k := stuff)]]
";
var d = await LintAsync(code, PythonVersions.Required_Python38X);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task UnresolvedFromImport() {
const string code = @"
from thismoduledoesnotexist import something
something()
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task AssignedSelf() {
const string code = @"
class DocEnum(Enum):
def __new__(cls, value, doc=None):
self = object.__new__(cls)
self._value_ = value
if doc is not None:
self.__doc__ = doc
return self
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task Metaclass() {
const string code = @"
class MyMetaclass(type):
pass
MyClass = MyMetaclass('MyClass', (), {})
class Subclass(MyClass):
pass
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
[TestMethod, Priority(0)]
public async Task AugmentedAssignToUndefined() {
const string code = @"
x += 1
";
var d = await LintAsync(code);
d.Should().HaveCount(1);
d[0].ErrorCode.Should().Be(ErrorCodes.UndefinedVariable);
d[0].SourceSpan.Should().Be(2, 1, 2, 2);
}
[TestMethod, Priority(0)]
public async Task PlatformSpecific() {
const string code = @"
import sys
if sys.platform == 'linux':
aVariable='Hello Linux'
print(aVariable)
else:
aVariable = 'Hello Other''
print(aVariable)
";
var d = await LintAsync(code);
d.Should().BeEmpty();
}
private async Task<IReadOnlyList<DiagnosticsEntry>> LintAsync(string code, InterpreterConfiguration configuration = null) {
var analysis = await GetAnalysisAsync(code, configuration ?? PythonVersions.LatestAvailable3X);
var a = Services.GetService<IPythonAnalyzer>();
return a.LintModule(analysis.Document);
}
private class AnalysisOptionsProvider : IAnalysisOptionsProvider {
public AnalysisOptions Options { get; } = new AnalysisOptions();
}
}
}