/
python2eval.test
449 lines (402 loc) · 10.4 KB
/
python2eval.test
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
-- Test cases for type checking mypy programs using full stubs and running
-- using CPython (Python 2 mode).
--
-- These are mostly regression tests -- no attempt is made to make these
-- complete.
[case testAbs2_python2]
n = None # type: int
f = None # type: float
n = abs(1)
abs(1) + 'x' # Error
f = abs(1.1)
abs(1.1) + 'x' # Error
[out]
_program.py:4: error: Unsupported operand types for + ("int" and "str")
_program.py:6: error: Unsupported operand types for + ("float" and "str")
[case testUnicode_python2]
x = unicode('xyz', 'latin1')
print x
x = u'foo'
print repr(x)
[out]
xyz
u'foo'
[case testXrangeAndRange_python2]
for i in xrange(2):
print i
for i in range(3):
print i
[out]
0
1
0
1
2
[case testIterator_python2]
import typing, sys
x = iter('bar')
print x.next(), x.next()
[out]
b a
[case testEncodeAndDecode_python2]
print 'a'.encode('latin1')
print 'b'.decode('latin1')
print u'c'.encode('latin1')
print u'd'.decode('latin1')
[out]
a
b
c
d
[case testHasKey_python2]
d = {1: 'x'}
print d.has_key(1)
print d.has_key(2)
[out]
True
False
[case testIntegerDivision_python2]
x = 1 / 2
x()
[out]
_program.py:2: error: "int" not callable
[case testFloatDivision_python2]
x = 1.0 / 2.0
x = 1.0 / 2
x = 1 / 2.0
x = 1.5
[out]
[case testAnyStr_python2]
from typing import AnyStr
def f(x): # type: (AnyStr) -> AnyStr
if isinstance(x, str):
return 'foo'
else:
return u'zar'
print f('')
print f(u'')
[out]
foo
zar
[case testGenericPatterns_python2]
from typing import Pattern
import re
p = None # type: Pattern[unicode]
p = re.compile(u'foo*')
b = None # type: Pattern[str]
b = re.compile('foo*')
print(p.match(u'fooo').group(0))
[out]
fooo
[case testGenericMatch_python2]
from typing import Match
import re
def f(m): # type: (Match[str]) -> None
print(m.group(0))
f(re.match('x*', 'xxy'))
[out]
xx
[case testFromFuturePrintFunction_python2]
from __future__ import print_function
print('a', 'b')
[out]
a b
[case testFromFutureImportUnicodeLiterals_python2]
from __future__ import unicode_literals
print '>', ['a', b'b', u'c']
[out]
> [u'a', 'b', u'c']
[case testUnicodeLiteralsKwargs_python2]
from __future__ import unicode_literals
def f(**kwargs): # type: (...) -> None
pass
params = {'a': 'b'}
f(**params)
[out]
[case testUnicodeStringKwargs_python2]
def f(**kwargs): # type: (...) -> None
pass
params = {u'a': 'b'}
f(**params)
[out]
[case testStrKwargs_python2]
def f(**kwargs): # type: (...) -> None
pass
params = {'a': 'b'}
f(**params)
[out]
[case testFromFutureImportUnicodeLiterals2_python2]
from __future__ import unicode_literals
def f(x): # type: (str) -> None
pass
f(b'')
f(u'')
f('')
[out]
_program.py:5: error: Argument 1 to "f" has incompatible type "unicode"; expected "str"
_program.py:6: error: Argument 1 to "f" has incompatible type "unicode"; expected "str"
[case testStrUnicodeCompatibility_python2]
def f(s): # type: (unicode) -> None
pass
f(u'')
f('')
[out]
[case testStrUnicodeCompatibilityInBuiltins_python2]
'x'.count('x')
'x'.count(u'x')
[out]
[case testTupleAsSubtypeOfSequence_python2]
from typing import TypeVar, Sequence
T = TypeVar('T')
def f(a): # type: (Sequence[T]) -> None
print a
f(tuple())
[out]
()
[case testIOTypes_python2]
from typing import IO, TextIO, BinaryIO, Any
class X(IO[str]): pass
class Y(TextIO): pass
class Z(BinaryIO): pass
[out]
[case testOpenReturnType_python2]
import typing
f = open('/tmp/xyz', 'w')
f.write(u'foo')
f.write('bar')
f.close()
[out]
_program.py:3: error: Argument 1 to "write" of "IO" has incompatible type "unicode"; expected "str"
[case testPrintFunctionWithFileArg_python2]
from __future__ import print_function
import typing
if 1 == 2: # Don't want to run the code below, since it would create a file.
f = open('/tmp/xyz', 'w')
print('foo', file=f)
f.close()
print('ok')
[out]
ok
[case testStringIO_python2]
import typing
import io
c = io.StringIO()
c.write(u'\x89')
print(repr(c.getvalue()))
[out]
u'\x89'
[case testBytesIO_python2]
import typing
import io
c = io.BytesIO()
c.write('\x89')
print(repr(c.getvalue()))
[out]
'\x89'
[case testTextIOWrapper_python2]
import typing
import io
b = io.BytesIO(u'\xab'.encode('utf8'))
w = io.TextIOWrapper(b, encoding='utf8')
print(repr(w.read()))
[out]
u'\xab'
[case testIoOpen_python2]
import typing
import io
if 1 == 2: # Only type check, do not execute
f = io.open('/tmp/xyz', 'w', encoding='utf8')
f.write(u'\xab')
f.close()
print 'ok'
[out]
ok
[case testStrAdd_python2]
import typing
s = ''
u = u''
n = 0
if int():
n = s + '' # E
s = s + u'' # E
[out]
_program.py:6: error: Incompatible types in assignment (expression has type "str", variable has type "int")
_program.py:7: error: Incompatible types in assignment (expression has type "unicode", variable has type "str")
[case testStrJoin_python2]
s = ''
u = u''
n = 0
if int():
n = ''.join(['']) # Error
if int():
s = ''.join([u'']) # Error
[out]
_program.py:5: error: Incompatible types in assignment (expression has type "str", variable has type "int")
_program.py:7: error: Incompatible types in assignment (expression has type "unicode", variable has type "str")
[case testNamedTuple_python2]
from typing import NamedTuple
from collections import namedtuple
X = namedtuple('X', ['a', 'b'])
x = X(a=1, b='s')
x.c
x.a
N = NamedTuple(u'N', [(u'x', int)])
n = namedtuple(u'n', u'x y')
[out]
_program.py:5: error: "X" has no attribute "c"
[case testAssignToComplexReal_python2]
import typing
x = 4j
y = x.real
if int():
y = x # Error
x.imag = 2.0 # Error
[out]
_program.py:5: error: Incompatible types in assignment (expression has type "complex", variable has type "float")
_program.py:6: error: Property "imag" defined in "complex" is read-only
[case testComplexArithmetic_python2]
import typing
print 5 + 8j
print 3j * 2.0
print 4j / 2.0
[out]
(5+8j)
6j
2j
[case testSuperNew_python2]
from typing import Dict, Any
class MyType(type):
def __new__(cls, name, bases, namespace):
# type: (str, tuple, Dict[str, Any]) -> Any
return super(MyType, cls).__new__(cls, name + 'x', bases, namespace)
class A(object):
__metaclass__ = MyType
print(type(A()).__name__)
[out]
Ax
[case testUnicodeAndOverloading_python2]
from m import f
f(1)
f('')
f(u'')
f(b'')
[file m.pyi]
from typing import overload
@overload
def f(x): # type: (bytearray) -> int
pass
@overload
def f(x): # type: (unicode) -> int
pass
[out]
_program.py:2: error: No overload variant of "f" matches argument type "int"
_program.py:2: note: Possible overload variants:
_program.py:2: note: def f(x: bytearray) -> int
_program.py:2: note: def f(x: unicode) -> int
[case testByteArrayStrCompatibility_python2]
def f(x): # type: (str) -> None
pass
f(bytearray('foo'))
[case testAbstractProperty_python2]
from abc import abstractproperty, ABCMeta
class A:
__metaclass__ = ABCMeta
@abstractproperty
def x(self): # type: () -> int
pass
class B(A):
@property
def x(self): # type: () -> int
return 3
b = B()
print b.x + 1
[out]
4
[case testReModuleBytes_python2]
# Regression tests for various overloads in the re module -- bytes version
import re
if False:
bre = b'a+'
bpat = re.compile(bre)
bpat = re.compile(bpat)
re.search(bre, b'').groups()
re.search(bre, u'')
re.search(bpat, b'').groups()
re.search(bpat, u'')
# match(), split(), findall(), finditer() are much the same, so skip those.
# sub(), subn() have more overloads and we are checking these:
re.sub(bre, b'', b'') + b''
re.sub(bpat, b'', b'') + b''
re.sub(bre, lambda m: b'', b'') + b''
re.sub(bpat, lambda m: b'', b'') + b''
re.subn(bre, b'', b'')[0] + b''
re.subn(bpat, b'', b'')[0] + b''
re.subn(bre, lambda m: b'', b'')[0] + b''
re.subn(bpat, lambda m: b'', b'')[0] + b''
[out]
[case testReModuleString_python2]
# Regression tests for various overloads in the re module -- string version
import re
ure = u'a+'
upat = re.compile(ure)
upat = re.compile(upat)
re.search(ure, u'a').groups()
re.search(ure, b'') # This ought to be an error, but isn't because of bytes->unicode equivalence
re.search(upat, u'a').groups()
re.search(upat, b'') # This ought to be an error, but isn't because of bytes->unicode equivalence
# match(), split(), findall(), finditer() are much the same, so skip those.
# sus(), susn() have more overloads and we are checking these:
re.sub(ure, u'', u'') + u''
re.sub(upat, u'', u'') + u''
re.sub(ure, lambda m: u'', u'') + u''
re.sub(upat, lambda m: u'', u'') + u''
re.subn(ure, u'', u'')[0] + u''
re.subn(upat, u'', u'')[0] + u''
re.subn(ure, lambda m: u'', u'')[0] + u''
re.subn(upat, lambda m: u'', u'')[0] + u''
[out]
[case testYieldRegressionTypingAwaitable_python2]
# Make sure we don't reference typing.Awaitable in Python 2 mode.
def g(): # type: () -> int
yield
[out]
_program.py:2: error: The return type of a generator function should be "Generator" or one of its supertypes
[case testOsPathJoinWorksWithAny_python2]
import os
def f(): # no annotation
return 'tests'
path = 'test'
path = os.path.join(f(), 'test.py')
[out]
[case testBytesWorkInPython2WithFullStubs_python2]
MYPY = False
if MYPY:
import lib
[file lib.pyi]
x = b'abc'
[out]
[case testDefaultDictInference]
from collections import defaultdict
def foo() -> None:
x = defaultdict(list)
x['lol'].append(10)
reveal_type(x)
[out]
_testDefaultDictInference.py:5: note: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
[case testIgnorePython3StdlibStubs_python2]
from collections import abc
[out]
_testIgnorePython3StdlibStubs_python2.py:1: error: Module "collections" has no attribute "abc"
[case testNoApprovedPython2StubInstalled_python2]
# flags: --ignore-missing-imports
import scribe
from scribe import x
import maxminddb
import foobar_asdf
[out]
_testNoApprovedPython2StubInstalled_python2.py:2: error: Library stubs not installed for "scribe" (or incompatible with Python 2.7)
_testNoApprovedPython2StubInstalled_python2.py:2: note: Hint: "python3 -m pip install types-scribe"
_testNoApprovedPython2StubInstalled_python2.py:2: note: (or run "mypy --install-types" to install all missing stub packages)
_testNoApprovedPython2StubInstalled_python2.py:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
_testNoApprovedPython2StubInstalled_python2.py:4: error: Library stubs not installed for "maxminddb" (or incompatible with Python 2.7)
_testNoApprovedPython2StubInstalled_python2.py:4: note: Hint: "python3 -m pip install types-maxminddb"