From 5718dfff79b62f75abb2d7ecbbfc089f02548099 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Tue, 26 Jul 2022 12:53:11 -0700 Subject: [PATCH] No longer support checking Python 2 (#13135) Linking #12237 --- mypy/main.py | 5 + mypy/test/helpers.py | 5 +- mypy/test/testdeps.py | 4 +- mypy/test/testparse.py | 4 +- mypy/test/testpythoneval.py | 18 +- mypy/test/testtransform.py | 3 +- test-data/unit/check-async-await.test | 5 - test-data/unit/check-attr.test | 35 +- test-data/unit/check-classes.test | 78 +- test-data/unit/check-columns.test | 46 -- test-data/unit/check-ctypes.test | 18 - test-data/unit/check-errorcodes.test | 94 --- test-data/unit/check-expressions.test | 129 ---- test-data/unit/check-fastparse.test | 153 ---- test-data/unit/check-flags.test | 34 - test-data/unit/check-formatting.test | 93 --- test-data/unit/check-functions.test | 38 - test-data/unit/check-ignore.test | 5 - test-data/unit/check-inference.test | 7 - test-data/unit/check-isinstance.test | 20 - test-data/unit/check-literal.test | 434 ----------- test-data/unit/check-modules.test | 57 -- test-data/unit/check-namedtuple.test | 10 - test-data/unit/check-newsemanal.test | 27 - test-data/unit/check-overloading.test | 69 -- test-data/unit/check-python2.test | 444 ----------- test-data/unit/check-reports.test | 11 - test-data/unit/check-tuples.test | 34 - test-data/unit/check-typeddict.test | 24 - test-data/unit/check-unreachable-code.test | 51 -- test-data/unit/cmdline.test | 44 +- test-data/unit/deps-expressions.test | 30 - test-data/unit/deps-statements.test | 50 -- test-data/unit/deps-types.test | 56 -- test-data/unit/deps.test | 57 -- test-data/unit/fine-grained-blockers.test | 20 - test-data/unit/fine-grained-modules.test | 2 +- test-data/unit/fine-grained-suggest.test | 13 - test-data/unit/fine-grained.test | 197 ----- test-data/unit/parse-python2.test | 809 --------------------- test-data/unit/python2eval.test | 449 ------------ test-data/unit/semanal-python2.test | 76 -- 42 files changed, 42 insertions(+), 3716 deletions(-) delete mode 100644 test-data/unit/check-python2.test delete mode 100644 test-data/unit/parse-python2.test delete mode 100644 test-data/unit/python2eval.test delete mode 100644 test-data/unit/semanal-python2.test diff --git a/mypy/main.py b/mypy/main.py index 95f420b5f9a2..619147a1c277 100644 --- a/mypy/main.py +++ b/mypy/main.py @@ -955,6 +955,11 @@ def set_strict_flags() -> None: # The python_version is either the default, which can be overridden via a config file, # or stored in special_opts and is passed via the command line. options.python_version = special_opts.python_version or options.python_version + if options.python_version < (3,): + parser.error( + "Mypy no longer supports checking Python 2 code. " + "Consider pinning to mypy<0.980 if you need to check Python 2 code." + ) try: infer_python_executable(options, special_opts) except PythonExecutableInferenceError as e: diff --git a/mypy/test/helpers.py b/mypy/test/helpers.py index 78b5d4c06ff4..2f97a0851941 100644 --- a/mypy/test/helpers.py +++ b/mypy/test/helpers.py @@ -286,9 +286,7 @@ def num_skipped_suffix_lines(a1: List[str], a2: List[str]) -> int: def testfile_pyversion(path: str) -> Tuple[int, int]: - if path.endswith('python2.test'): - return defaults.PYTHON2_VERSION - elif path.endswith('python310.test'): + if path.endswith('python310.test'): return 3, 10 else: return defaults.PYTHON3_VERSION @@ -296,6 +294,7 @@ def testfile_pyversion(path: str) -> Tuple[int, int]: def testcase_pyversion(path: str, testcase_name: str) -> Tuple[int, int]: if testcase_name.endswith('python2'): + raise ValueError(testcase_name) return defaults.PYTHON2_VERSION else: return testfile_pyversion(path) diff --git a/mypy/test/testdeps.py b/mypy/test/testdeps.py index 03869b67316a..1ca36b6ca4bb 100644 --- a/mypy/test/testdeps.py +++ b/mypy/test/testdeps.py @@ -6,7 +6,7 @@ from typing import List, Tuple, Dict, Optional, Set from typing_extensions import DefaultDict -from mypy import build, defaults +from mypy import build from mypy.modulefinder import BuildSource from mypy.errors import CompileError from mypy.nodes import MypyFile, Expression @@ -29,8 +29,6 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: src = '\n'.join(testcase.input) dump_all = '# __dump_all__' in src options = parse_options(src, testcase, incremental_step=1) - if testcase.name.endswith('python2'): - options.python_version = defaults.PYTHON2_VERSION options.use_builtins_fixtures = True options.show_traceback = True options.cache_dir = os.devnull diff --git a/mypy/test/testparse.py b/mypy/test/testparse.py index ec9930bd26b7..f75452c58860 100644 --- a/mypy/test/testparse.py +++ b/mypy/test/testparse.py @@ -31,9 +31,7 @@ def test_parser(testcase: DataDrivenTestCase) -> None: """ options = Options() - if testcase.file.endswith('python2.test'): - options.python_version = defaults.PYTHON2_VERSION - elif testcase.file.endswith('python310.test'): + if testcase.file.endswith('python310.test'): options.python_version = (3, 10) else: options.python_version = defaults.PYTHON3_VERSION diff --git a/mypy/test/testpythoneval.py b/mypy/test/testpythoneval.py index 770738294755..4fcf6e063268 100644 --- a/mypy/test/testpythoneval.py +++ b/mypy/test/testpythoneval.py @@ -18,15 +18,12 @@ import sys from tempfile import TemporaryDirectory -import pytest - from typing import List from mypy.defaults import PYTHON3_VERSION from mypy.test.config import test_temp_dir from mypy.test.data import DataDrivenTestCase, DataSuite from mypy.test.helpers import assert_string_arrays_equal, split_lines -from mypy.util import try_find_python2_interpreter from mypy import api # Path to Python 3 interpreter @@ -36,7 +33,6 @@ class PythonEvaluationSuite(DataSuite): files = ['pythoneval.test', - 'python2eval.test', 'pythoneval-asyncio.test'] cache_dir = TemporaryDirectory() @@ -59,18 +55,8 @@ def test_python_evaluation(testcase: DataDrivenTestCase, cache_dir: str) -> None '--no-silence-site-packages', '--no-error-summary', ] - py2 = testcase.name.lower().endswith('python2') - if py2: - mypy_cmdline.append('--py2') - interpreter = try_find_python2_interpreter() - if interpreter is None: - # Skip, can't find a Python 2 interpreter. - pytest.skip() - # placate the type checker - return - else: - interpreter = python3_path - mypy_cmdline.append(f"--python-version={'.'.join(map(str, PYTHON3_VERSION))}") + interpreter = python3_path + mypy_cmdline.append(f"--python-version={'.'.join(map(str, PYTHON3_VERSION))}") m = re.search('# flags: (.*)$', '\n'.join(testcase.input), re.MULTILINE) if m: diff --git a/mypy/test/testtransform.py b/mypy/test/testtransform.py index bd400b254ff4..3b9b77a9cf58 100644 --- a/mypy/test/testtransform.py +++ b/mypy/test/testtransform.py @@ -22,8 +22,7 @@ class TransformSuite(DataSuite): 'semanal-types.test', 'semanal-modules.test', 'semanal-statements.test', - 'semanal-abstractclasses.test', - 'semanal-python2.test'] + 'semanal-abstractclasses.test'] native_sep = True def run_case(self, testcase: DataDrivenTestCase) -> None: diff --git a/test-data/unit/check-async-await.test b/test-data/unit/check-async-await.test index 950c64098cf0..195e70cf5880 100644 --- a/test-data/unit/check-async-await.test +++ b/test-data/unit/check-async-await.test @@ -362,11 +362,6 @@ async def g(): main:3: error: "yield from" in async function main:5: error: "yield from" in async function -[case testNoAsyncDefInPY2_python2] - -async def f(): # E: invalid syntax - pass - [case testYieldFromNoAwaitable] from typing import Any, Generator diff --git a/test-data/unit/check-attr.test b/test-data/unit/check-attr.test index 4e09e10a6726..c5b64ee61376 100644 --- a/test-data/unit/check-attr.test +++ b/test-data/unit/check-attr.test @@ -35,7 +35,7 @@ A(1, 2, 3, 4) # E: Argument 2 to "A" has incompatible type "int"; expected "Lis A(1, [2], '3', 4, 5) # E: Too many arguments for "A" [builtins fixtures/list.pyi] -[case testAttrsPython2Annotations] +[case testAttrsTypeComments] import attr from typing import List, ClassVar @attr.s @@ -1032,28 +1032,6 @@ class C: reveal_type(C) # N: Revealed type is "def (a: builtins.int, b: builtins.int) -> __main__.C" [builtins fixtures/bool.pyi] -[case testAttrsNewStyleClassPy2] -# flags: --py2 -import attr -@attr.s -class Good(object): - pass -@attr.s -class Bad: # E: attrs only works with new-style classes - pass -@attr.s -class SubclassOfBad(Bad): - pass -[builtins_py2 fixtures/bool.pyi] - -[case testAttrsAutoAttribsPy2] -# flags: --py2 -import attr -@attr.s(auto_attribs=True) # E: auto_attribs is not supported in Python 2 -class A(object): - x = attr.ib() -[builtins_py2 fixtures/bool.pyi] - [case testAttrsFrozenSubclass] import attr @@ -1291,17 +1269,6 @@ class C: [builtins fixtures/attr.pyi] -[case testAttrsKwOnlyPy2] -# flags: --py2 -import attr -@attr.s(kw_only=True) # E: kw_only is not supported in Python 2 -class A(object): - x = attr.ib() -@attr.s -class B(object): - x = attr.ib(kw_only=True) # E: kw_only is not supported in Python 2 -[builtins_py2 fixtures/bool.pyi] - [case testAttrsDisallowUntypedWorksForward] # flags: --disallow-untyped-defs import attr diff --git a/test-data/unit/check-classes.test b/test-data/unit/check-classes.test index ca508c9e6264..1572ab2f8c8a 100644 --- a/test-data/unit/check-classes.test +++ b/test-data/unit/check-classes.test @@ -2207,7 +2207,7 @@ reveal_type(Num3() + Num1()) # N: Revealed type is "__main__.Num3" reveal_type(Num2() + Num3()) # N: Revealed type is "__main__.Num2" reveal_type(Num3() + Num2()) # N: Revealed type is "__main__.Num3" -[case testDivReverseOperatorPython3] +[case testDivReverseOperator] # No error: __div__ has no special meaning in Python 3 class A1: def __div__(self, x: B1) -> int: ... @@ -2222,37 +2222,6 @@ class B2: A1() / B1() # E: Unsupported left operand type for / ("A1") reveal_type(A2() / B2()) # N: Revealed type is "builtins.int" -[case testDivReverseOperatorPython2] -# flags: --python-version 2.7 - -# Note: if 'from __future__ import division' is called, we use -# __truediv__. Otherwise, we use __div__. So, we check both: -class A1: - def __div__(self, x): - # type: (B1) -> int - pass -class B1: - def __rdiv__(self, x): # E: Signatures of "__rdiv__" of "B1" and "__div__" of "A1" are unsafely overlapping - # type: (A1) -> str - pass - -class A2: - def __truediv__(self, x): - # type: (B2) -> int - pass -class B2: - def __rtruediv__(self, x): # E: Signatures of "__rtruediv__" of "B2" and "__truediv__" of "A2" are unsafely overlapping - # type: (A2) -> str - pass - -# That said, mypy currently doesn't handle the actual division operation very -# gracefully -- it doesn't correctly switch to using __truediv__ when -# 'from __future__ import division' is included, it doesn't display a very -# graceful error if __div__ is missing but __truediv__ is present... -# Also see https://github.com/python/mypy/issues/2048 -reveal_type(A1() / B1()) # N: Revealed type is "builtins.int" -A2() / B2() # E: "A2" has no attribute "__div__" - [case testReverseOperatorMethodForwardIsAny] from typing import Any def deco(f: Any) -> Any: return f @@ -2502,17 +2471,7 @@ reveal_type(B() + y) # N: Revealed type is "Union[__main__.Out2, __main__.Out4] reveal_type(x + C()) # N: Revealed type is "Union[__main__.Out3, __main__.Out2]" reveal_type(x + D()) # N: Revealed type is "Union[__main__.Out1, __main__.Out4]" -[case testOperatorDoubleUnionDivisionPython2] -# flags: --python-version 2.7 -from typing import Union -def f(a): - # type: (Union[int, float]) -> None - a /= 1.1 - b = a / 1.1 - reveal_type(b) # N: Revealed type is "builtins.float" -[builtins_py2 fixtures/ops.pyi] - -[case testOperatorDoubleUnionDivisionPython3] +[case testOperatorDoubleUnionDivision] from typing import Union def f(a): # type: (Union[int, float]) -> None @@ -5084,16 +5043,6 @@ reveal_type(type(A).x) # N: Revealed type is "builtins.int" reveal_type(type(B).x) # N: Revealed type is "builtins.int" [builtins fixtures/tuple.pyi] -[case testSixMetaclass_python2] -import six -class M(type): - x = 5 -class A(six.with_metaclass(M)): pass -@six.add_metaclass(M) -class B: pass -reveal_type(type(A).x) # N: Revealed type is "builtins.int" -reveal_type(type(B).x) # N: Revealed type is "builtins.int" - [case testFromSixMetaclass] from six import with_metaclass, add_metaclass class M(type): @@ -5217,13 +5166,6 @@ class CQA(Q1): pass # E: Inconsistent metaclass structure for "CQA" class CQW(six.with_metaclass(M, Q1)): pass # E: Inconsistent metaclass structure for "CQW" [builtins fixtures/tuple.pyi] -[case testSixMetaclassErrors_python2] -# flags: --python-version 2.7 -import six -class M(type): pass -class C4(six.with_metaclass(M)): # E: Multiple metaclass definitions - __metaclass__ = M - [case testSixMetaclassAny] import t # type: ignore import six @@ -5244,13 +5186,6 @@ class A(future.utils.with_metaclass(M)): pass reveal_type(type(A).x) # N: Revealed type is "builtins.int" [builtins fixtures/tuple.pyi] -[case testFutureMetaclass_python2] -import future.utils -class M(type): - x = 5 -class A(future.utils.with_metaclass(M)): pass -reveal_type(type(A).x) # N: Revealed type is "builtins.int" - [case testFromFutureMetaclass] from future.utils import with_metaclass class M(type): @@ -5336,13 +5271,6 @@ class Q1(metaclass=M1): pass class CQW(future.utils.with_metaclass(M, Q1)): pass # E: Inconsistent metaclass structure for "CQW" [builtins fixtures/tuple.pyi] -[case testFutureMetaclassErrors_python2] -# flags: --python-version 2.7 -import future.utils -class M(type): pass -class C4(future.utils.with_metaclass(M)): # E: Multiple metaclass definitions - __metaclass__ = M - [case testFutureMetaclassAny] import t # type: ignore import future.utils @@ -7323,7 +7251,7 @@ def foo(self: Any) -> str: from typing import Any, Callable, TypeVar class Parent: - foo = Callable[..., int] + foo = Callable[..., int] class bar: pass import typing as baz diff --git a/test-data/unit/check-columns.test b/test-data/unit/check-columns.test index 219befe1bb7d..7c4681c7a709 100644 --- a/test-data/unit/check-columns.test +++ b/test-data/unit/check-columns.test @@ -170,22 +170,6 @@ z: Iterable[bad] # E:13: Variable "__main__.bad" is not valid as a type \ h: bad[int] # E:4: Variable "__main__.bad" is not valid as a type \ # N:4: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases -[case testColumnInvalidType_python2] - -from typing import Iterable - -bad = 0 - -if int(): - def g(x): # E:5: Variable "__main__.bad" is not valid as a type \ - # N:5: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases - # type: (bad) -> None - y = 0 # type: bad # E:9: Variable "__main__.bad" is not valid as a type \ - # N:9: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases - - z = () # type: Iterable[bad] # E:5: Variable "__main__.bad" is not valid as a type \ - # N:5: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases - [case testColumnFunctionMissingTypeAnnotation] # flags: --disallow-untyped-defs if int(): @@ -216,14 +200,6 @@ def f(x, y): pass (f()) # E:2: Missing positional arguments "x", "y" in call to "f" (f(y=1)) # E:2: Missing positional argument "x" in call to "f" -[case testColumnTooFewSuperArgs_python2] -class A: - def f(self): - pass -class B(A): - def f(self): # type: () -> None - super().f() # E:9: Too few arguments for "super" - [case testColumnListOrDictItemHasIncompatibleType] from typing import List, Dict x: List[int] = [ @@ -316,12 +292,6 @@ if int(): # type: (int) -> None pass -[case testColumnTypeSignatureHasTooFewArguments_python2] -if int(): - def f(x, y): # E:5: Type signature has too few arguments - # type: (int) -> None - pass - [case testColumnRevealedType] if int(): reveal_type(1) # N:17: Revealed type is "Literal[1]?" @@ -373,22 +343,6 @@ class B(A): def x(self) -> int: pass [builtins fixtures/property.pyi] -[case testColumnProperty_python2] -class A: - @property - def x(self): # type: () -> int - pass - - @x.setter - def x(self, x): # type: (int) -> None - pass - -class B(A): - @property # E:5: Read-only property cannot override read-write property - def x(self): # type: () -> int - pass -[builtins_py2 fixtures/property_py2.pyi] - [case testColumnOverloaded] from typing import overload, Any class A: diff --git a/test-data/unit/check-ctypes.test b/test-data/unit/check-ctypes.test index 17b87904e9c6..605c54fb5694 100644 --- a/test-data/unit/check-ctypes.test +++ b/test-data/unit/check-ctypes.test @@ -92,15 +92,6 @@ import ctypes ca = (ctypes.c_char_p * 0)() [builtins fixtures/floatdict.pyi] -[case testCtypesCharArrayAttrsPy2] -# flags: --py2 -import ctypes - -ca = (ctypes.c_char * 4)('a', 'b', 'c', '\x00') -reveal_type(ca.value) # N: Revealed type is "builtins.str" -reveal_type(ca.raw) # N: Revealed type is "builtins.str" -[builtins_py2 fixtures/floatdict_python2.pyi] - [case testCtypesWcharArrayAttrs] import ctypes @@ -109,15 +100,6 @@ reveal_type(wca.value) # N: Revealed type is "builtins.str" wca.raw # E: Array attribute "raw" is only available with element type "c_char", not "c_wchar" [builtins fixtures/floatdict.pyi] -[case testCtypesWcharArrayAttrsPy2] -# flags: --py2 -import ctypes - -wca = (ctypes.c_wchar * 4)(u'a', u'b', u'c', u'\x00') -reveal_type(wca.value) # N: Revealed type is "builtins.unicode" -wca.raw # E: Array attribute "raw" is only available with element type "c_char", not "c_wchar" -[builtins_py2 fixtures/floatdict_python2.pyi] - [case testCtypesCharUnionArrayAttrs] import ctypes from typing import Union diff --git a/test-data/unit/check-errorcodes.test b/test-data/unit/check-errorcodes.test index 69aa3229f4b5..f1a6f3c77ada 100644 --- a/test-data/unit/check-errorcodes.test +++ b/test-data/unit/check-errorcodes.test @@ -57,22 +57,6 @@ x: 'a b' # type: ignore[valid-type] for v in x: # type: int, int # type: ignore[syntax] pass -[case testErrorCodeSyntaxError_python2] -1 '' # E: invalid syntax [syntax] - -[case testErrorCodeSyntaxError2_python2] -def f(): # E: Type signature has too many arguments [syntax] - # type: (int) -> None - 1 - -x = 0 # type: x y # E: syntax error in type comment "x y" [syntax] - -[case testErrorCodeSyntaxError3_python2] -def f(): pass -for v in f(): # type: int, int # E: Syntax error in type annotation [syntax] \ - # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn) - pass - [case testErrorCodeIgnore1] 'x'.foobar # type: ignore[attr-defined] 'x'.foobar # type: ignore[xyz] # E: "str" has no attribute "foobar" [attr-defined] \ @@ -85,18 +69,6 @@ b = 'x'.foobar # type: int # type: ignore[xyz] # E: "str" has no attribute "f # N: Error code "attr-defined" not covered by "type: ignore" comment c = 'x'.foobar # type: int # type: ignore -[case testErrorCodeIgnore1_python2] -'x'.foobar # type: ignore[attr-defined] -'x'.foobar # type: ignore[xyz] # E: "str" has no attribute "foobar" [attr-defined] \ - # N: Error code "attr-defined" not covered by "type: ignore" comment -'x'.foobar # type: ignore - -[case testErrorCodeIgnore2_python2] -a = 'x'.foobar # type: int # type: ignore[attr-defined] -b = 'x'.foobar # type: int # type: ignore[xyz] # E: "str" has no attribute "foobar" [attr-defined] \ - # N: Error code "attr-defined" not covered by "type: ignore" comment -c = 'x'.foobar # type: int # type: ignore - [case testErrorCodeIgnoreMultiple1] a = 'x'.foobar(b) # type: ignore[name-defined, attr-defined] a = 'x'.foobar(b) # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \ @@ -109,18 +81,6 @@ a = 'x'.foobar(b) # type: int # type: ignore[name-defined, attr-defined] b = 'x'.foobar(b) # type: int # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \ # N: Error code "attr-defined" not covered by "type: ignore" comment -[case testErrorCodeIgnoreMultiple1_python2] -a = 'x'.foobar(b) # type: ignore[name-defined, attr-defined] -a = 'x'.foobar(b) # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \ - # N: Error code "attr-defined" not covered by "type: ignore" comment -a = 'x'.foobar(b) # type: ignore[xyz, w, attr-defined] # E: Name "b" is not defined [name-defined] \ - # N: Error code "name-defined" not covered by "type: ignore" comment - -[case testErrorCodeIgnoreMultiple2_python2] -a = 'x'.foobar(b) # type: int # type: ignore[name-defined, attr-defined] -b = 'x'.foobar(b) # type: int # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \ - # N: Error code "attr-defined" not covered by "type: ignore" comment - [case testErrorCodeWarnUnusedIgnores1] # flags: --warn-unused-ignores x # type: ignore[name-defined, attr-defined] # E: Unused "type: ignore[attr-defined]" comment @@ -215,31 +175,10 @@ def h(x # type: xyz # type: ignore[foo] # E: Name "xyz" is not defined [name # type () -> None pass -[case testErrorCodeIgnoreAfterArgComment_python2] -def f(x # type: xyz # type: ignore[name-defined] # Comment - ): - # type () -> None - pass - -def g(x # type: xyz # type: ignore # Comment - ): - # type () -> None - pass - -def h(x # type: xyz # type: ignore[foo] # E: Name "xyz" is not defined [name-defined] \ - # N: Error code "name-defined" not covered by "type: ignore" comment - ): - # type () -> None - pass - [case testErrorCodeIgnoreWithNote] import nostub # type: ignore[import] from defusedxml import xyz # type: ignore[import] -[case testErrorCodeIgnoreWithNote_python2] -import nostub # type: ignore[import] -from defusedxml import xyz # type: ignore[import] - [case testErrorCodeBadIgnore] import nostub # type: ignore xyz # E: Invalid "type: ignore" comment [syntax] import nostub # type: ignore[ # E: Invalid "type: ignore" comment [syntax] @@ -273,22 +212,6 @@ main:4: error: Invalid "type: ignore" comment [syntax] main:5: error: Invalid "type: ignore" comment [syntax] main:6: error: Invalid "type: ignore" comment [syntax] -[case testErrorCodeBadIgnore_python2] -import nostub # type: ignore xyz -import nostub # type: ignore[xyz # Comment [x] -import nostub # type: ignore[xyz][xyz] -x = 0 # type: ignore[ -def f(x, # type: int # type: ignore[ - ): - # type: (...) -> None - pass -[out] -main:1: error: Invalid "type: ignore" comment [syntax] -main:2: error: Invalid "type: ignore" comment [syntax] -main:3: error: Invalid "type: ignore" comment [syntax] -main:4: error: Invalid "type: ignore" comment [syntax] -main:5: error: Invalid "type: ignore" comment [syntax] - [case testErrorCodeArgKindAndCount] def f(x: int) -> None: pass # N: "f" defined here f() # E: Missing positional argument "x" in call to "f" [call-arg] @@ -302,14 +225,6 @@ def h(x: int, y: int, z: int) -> None: pass h(y=1, z=1) # E: Missing positional argument "x" in call to "h" [call-arg] h(y=1) # E: Missing positional arguments "x", "z" in call to "h" [call-arg] -[case testErrorCodeSuperArgs_python2] -class A: - def f(self): - pass -class B(A): - def f(self): # type: () -> None - super().f() # E: Too few arguments for "super" [call-arg] - [case testErrorCodeArgType] def f(x: int) -> None: pass f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int" [arg-type] @@ -576,15 +491,6 @@ def g(x): # E: Type signature has too many arguments [syntax] # type: (int, int) -> None pass -[case testErrorCodeInvalidCommentSignature_python2] -def f(x): # E: Type signature has too few arguments [syntax] - # type: () -> None - pass - -def g(x): # E: Type signature has too many arguments [syntax] - # type: (int, int) -> None - pass - [case testErrorCodeNonOverlappingEquality] # flags: --strict-equality if int() == str(): # E: Non-overlapping equality check (left operand type: "int", right operand type: "str") [comparison-overlap] diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index fd10b82cc558..ab4f0d4e1b06 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -202,70 +202,6 @@ class C: pass [builtins fixtures/tuple.pyi] -[case testDivPython2] -# flags: --python-version 2.7 -class A(object): - def __div__(self, other): - # type: (A, str) -> str - return 'a' - -a = A() -reveal_type(a / 'b') # N: Revealed type is "builtins.str" -a / 1 # E: Unsupported operand types for / ("A" and "int") -[builtins fixtures/bool.pyi] - -[case testDivPython2FutureImport] -# flags: --python-version 2.7 -from __future__ import division - -class A(object): - def __truediv__(self, other): - # type: (A, str) -> str - return 'a' - -a = A() -reveal_type(a / 'b') # N: Revealed type is "builtins.str" -a / 1 # E: Unsupported operand types for / ("A" and "int") -[builtins fixtures/bool.pyi] - -[case testDivPython2FutureImportNotLeaking] -# flags: --python-version 2.7 -import m1 - -[file m1.py] -import m2 - -class A(object): - def __div__(self, other): - # type: (A, str) -> str - return 'a' - -a = A() -reveal_type(a / 'b') # N: Revealed type is "builtins.str" -a / 1 # E: Unsupported operand types for / ("A" and "int") -[file m2.py] -from __future__ import division -[builtins fixtures/bool.pyi] - -[case testDivPython2FutureImportNotLeaking2] -# flags: --python-version 2.7 -import m1 - -[file m1.py] -import m2 - -class A(object): - def __div__(self, other): - # type: (A, str) -> str - return 'a' - -a = A() -reveal_type(a / 'b') # N: Revealed type is "builtins.str" -a / 1 # E: Unsupported operand types for / ("A" and "int") -[file m2.py] -# empty -[builtins fixtures/bool.pyi] - [case testIntDiv] a, b, c = None, None, None # type: (A, B, C) if int(): @@ -533,53 +469,7 @@ class B: def __gt__(self, o: 'B') -> bool: pass [builtins fixtures/bool.pyi] -[case testCmp_python2] - -a, b, c, bo = None, None, None, None # type: (A, B, C, bool) -bo = a == a # E: Unsupported operand types for == ("A" and "A") -bo = a != a # E: Unsupported operand types for comparison ("A" and "A") -bo = a < b -bo = a > b -bo = b <= b -bo = b <= c -bo = b >= c # E: Unsupported operand types for comparison ("C" and "B") -bo = a >= b -bo = c >= b -bo = c <= b # E: Unsupported operand types for comparison ("B" and "C") -bo = a == c -bo = b == c # E: Unsupported operand types for == ("C" and "B") - -class A: - def __cmp__(self, o): - # type: ('B') -> bool - pass - def __eq__(self, o): - # type: ('int') -> bool - pass -class B: - def __cmp__(self, o): - # type: ('B') -> bool - pass - def __le__(self, o): - # type: ('C') -> bool - pass -class C: - def __cmp__(self, o): - # type: ('A') -> bool - pass - def __eq__(self, o): - # type: ('int') -> bool - pass - -[builtins_py2 fixtures/bool_py2.pyi] - -[case testDiv_python2] -10 / 'no' # E: Unsupported operand types for / ("int" and "str") -'no' / 10 # E: Unsupported operand types for / ("str" and "int") -[builtins_py2 fixtures/ops.pyi] - [case cmpIgnoredPy3] - a, b, bo = None, None, None # type: (A, B, bool) bo = a <= b # E: Unsupported left operand type for <= ("A") @@ -587,7 +477,6 @@ class A: def __cmp__(self, o: 'B') -> bool: pass class B: pass - [builtins fixtures/bool.pyi] [case testLeAndGe] @@ -2000,12 +1889,6 @@ bytearray(b'abc') in b'abcde' # OK on Python 3 [builtins fixtures/primitives.pyi] [typing fixtures/typing-medium.pyi] -[case testBytesVsByteArray_python2] -# flags: --strict-equality --py2 -b'hi' in bytearray(b'hi') -[builtins_py2 fixtures/python2.pyi] -[typing fixtures/typing-medium.pyi] - [case testStrictEqualityNoPromotePy3] # flags: --strict-equality 'a' == b'a' # E: Non-overlapping equality check (left operand type: "Literal['a']", right operand type: "Literal[b'a']") @@ -2265,18 +2148,6 @@ if f == 0: # E: Non-overlapping equality check (left operand type: "FileId", ri ... [builtins fixtures/bool.pyi] -[case testStrictEqualityPromotionsLiterals] -# flags: --strict-equality --py2 -from typing import Final - -U_FOO = u'foo' # type: Final - -if str() == U_FOO: - pass -assert u'foo' == 'foo' -assert u'foo' == u'bar' # E: Non-overlapping equality check (left operand type: "Literal[u'foo']", right operand type: "Literal[u'bar']") -[builtins_py2 fixtures/python2.pyi] - [case testStrictEqualityWithFixedLengthTupleInCheck] # flags: --strict-equality if 1 in ('x', 'y'): # E: Non-overlapping container check (element type: "int", container item type: "str") diff --git a/test-data/unit/check-fastparse.test b/test-data/unit/check-fastparse.test index b30581f0cfd3..848d91b1659d 100644 --- a/test-data/unit/check-fastparse.test +++ b/test-data/unit/check-fastparse.test @@ -30,38 +30,6 @@ def f(x): # E: Invalid type comment or annotation # type: (a + b) -> None pass -[case testFastParseInvalidTypes2] -# flags: --py2 -# All of these should not crash -from typing import Callable, Tuple, Iterable - -x = None # type: Tuple[int, str].x # E: Invalid type comment or annotation -a = None # type: Iterable[x].x # E: Invalid type comment or annotation -b = None # type: Tuple[x][x] # E: Invalid type comment or annotation -c = None # type: Iterable[x][x] # E: Invalid type comment or annotation -d = None # type: Callable[..., int][x] # E: Invalid type comment or annotation -e = None # type: Callable[..., int].x # E: Invalid type comment or annotation - -def f1(x): # E: Invalid type comment or annotation - # type: (Tuple[int, str].x) -> None - pass -def f2(x): # E: Invalid type comment or annotation - # type: (Iterable[x].x) -> None - pass -def f3(x): # E: Invalid type comment or annotation - # type: (Tuple[x][x]) -> None - pass -def f4(x): # E: Invalid type comment or annotation - # type: (Iterable[x][x]) -> None - pass -def f5(x): # E: Invalid type comment or annotation - # type: (Callable[..., int][x]) -> None - pass -def f6(x): # E: Invalid type comment or annotation - # type: (Callable[..., int].x) -> None - pass - - [case testFastParseInvalidTypes3] # flags: --python-version 3.6 # All of these should not crash @@ -208,42 +176,6 @@ def f(*, [builtins fixtures/dict.pyi] [out] -[case testFastParsePerArgumentAnnotations_python2] - -class A: pass -class B: pass -class C: pass -class D: pass -def f(a, # type: A - b = None, # type: B - *args # type: C - # kwargs not tested due to lack of 2.7 dict fixtures - ): - reveal_type(a) # N: Revealed type is "__main__.A" - reveal_type(b) # N: Revealed type is "Union[__main__.B, None]" - reveal_type(args) # N: Revealed type is "builtins.tuple[__main__.C, ...]" -[builtins fixtures/dict.pyi] -[out] - -[case testFastParsePerArgumentAnnotationsWithReturn_python2] - -class A: pass -class B: pass -class C: pass -class D: pass -def f(a, # type: A - b = None, # type: B - *args # type: C - # kwargs not tested due to lack of 2.7 dict fixtures - ): - # type: (...) -> int - reveal_type(a) # N: Revealed type is "__main__.A" - reveal_type(b) # N: Revealed type is "Union[__main__.B, None]" - reveal_type(args) # N: Revealed type is "builtins.tuple[__main__.C, ...]" - return "not an int" # E: Incompatible return value type (got "str", expected "int") -[builtins fixtures/dict.pyi] -[out] - [case testFasterParseTooManyArgumentsAnnotation] def f(): # E: Type signature has too many arguments # type: (int) -> None @@ -261,42 +193,6 @@ def f(x, y): # E: Type signature has too few arguments f(1, 2) f(1) # E: Missing positional argument "y" in call to "f" -[case testFasterParseTooManyArgumentsAnnotation_python2] -def f(): # E: Type signature has too many arguments - # type: (int) -> None - pass - -f() -f(1) # E: Too many arguments for "f" - -[case testFasterParseTooFewArgumentsAnnotation_python2] -def f(x, y): # E: Type signature has too few arguments - # type: (int) -> None - x() - y() - -f(1, 2) -f(1) # E: Missing positional argument "y" in call to "f" - -[case testFasterParseTypeCommentError_python2] -from typing import Tuple -def f(a): - # type: (Tuple(int, int)) -> int - pass -[out] -main:2: error: Invalid type comment or annotation -main:2: note: Suggestion: use Tuple[...] instead of Tuple(...) - -[case testFasterParseTypeErrorList_python2] -from typing import List -def f(a): - # type: (List(int)) -> int - pass -[builtins_py2 fixtures/floatdict_python2.pyi] -[out] -main:2: error: Invalid type comment or annotation -main:2: note: Suggestion: use List[...] instead of List(...) - [case testFasterParseTypeErrorCustom] from typing import TypeVar, Generic @@ -317,11 +213,6 @@ x = None # type: Any x @ 1 x @= 1 -[case testPrintStatementTrailingCommaFastParser_python2] - -print 0, -print 1, 2, - [case testFastParserShowsMultipleErrors] def f(x): # E: Type signature has too few arguments # type: () -> None @@ -405,34 +296,6 @@ def k(*, y, z, y): # E: Duplicate argument "y" in function definition lambda x, y, x: ... # E: Duplicate argument "x" in function definition -[case testFastParserDuplicateNames_python2] - -def f(x, y, z): - pass - -def g(x, y, x): # E: Duplicate argument "x" in function definition - pass - -def h(x, y, *x): # E: Duplicate argument "x" in function definition - pass - -def i(x, y, *z, **z): # E: Duplicate argument "z" in function definition - pass - -def j(x, (y, y), z): # E: Duplicate argument "y" in function definition - pass - -def k(x, (y, x)): # E: Duplicate argument "x" in function definition - pass - -def l((x, y), (z, x)): # E: Duplicate argument "x" in function definition - pass - -def m(x, ((x, y), z)): # E: Duplicate argument "x" in function definition - pass - -lambda x, (y, x): None # E: Duplicate argument "x" in function definition - [case testNoCrashOnImportFromStar] from pack import * [file pack/__init__.py] @@ -460,19 +323,3 @@ class Bla: def call() -> str: pass [builtins fixtures/module.pyi] - -[case testNoCrashOnImportFromStarPython2] -# flags: --py2 -from . import * # E: No parent module -- cannot perform relative import - -[case testSpuriousTrailingComma_python2] -from typing import Optional - -def update_state(tid, # type: int - vid, # type: int - update_ts=None, # type: Optional[float], - ): # type: (...) -> str - pass -[out] -main:3: error: Syntax error in type annotation -main:3: note: Suggestion: Is there a spurious trailing comma? diff --git a/test-data/unit/check-flags.test b/test-data/unit/check-flags.test index 5cda01fab855..0d3af684c9bb 100644 --- a/test-data/unit/check-flags.test +++ b/test-data/unit/check-flags.test @@ -1939,40 +1939,6 @@ no_implicit_optional = true module = 'm' no_implicit_optional = false - -[case testNoImplicitOptionalPerModulePython2] -# flags: --config-file tmp/mypy.ini --python-version 2.7 -import m - -[file m.py] -def f(a = None): - # type: (str) -> int - return 0 - -[file mypy.ini] -\[mypy] -no_implicit_optional = True -\[mypy-m] -no_implicit_optional = False - - -[case testNoImplicitOptionalPerModulePython2PyProjectTOML] -# flags: --config-file tmp/pyproject.toml --python-version 2.7 -import m - -[file m.py] -def f(a = None): - # type: (str) -> int - return 0 - -[file pyproject.toml] -\[tool.mypy] -no_implicit_optional = true -\[[tool.mypy.overrides]] -module = 'm' -no_implicit_optional = false - - [case testDisableErrorCode] # flags: --disable-error-code attr-defined x = 'should be fine' diff --git a/test-data/unit/check-formatting.test b/test-data/unit/check-formatting.test index 783c31c18770..5c0d0ed65292 100644 --- a/test-data/unit/check-formatting.test +++ b/test-data/unit/check-formatting.test @@ -34,19 +34,6 @@ xs: str '%(name)s' % {'name': b'value'} # E: On Python 3 formatting "b'abc'" with "%s" produces "b'abc'", not "abc"; use "%r" if this is desired behavior [builtins fixtures/primitives.pyi] -[case testStringInterpolationSBytesVsStrResultsPy2] -# flags: --python-version 2.7 -xs = 'x' -xu = u'x' - -reveal_type('%s' % xu) # N: Revealed type is "builtins.unicode" -reveal_type('%s, %d' % (u'abc', 42)) # N: Revealed type is "builtins.unicode" -reveal_type('%(key)s' % {'key': xu}) # N: Revealed type is "builtins.unicode" -reveal_type('%r' % xu) # N: Revealed type is "builtins.str" -reveal_type('%s' % xs) # N: Revealed type is "builtins.str" -[builtins fixtures/primitives.pyi] -[typing fixtures/typing-medium.pyi] - [case testStringInterpolationCount] '%d %d' % 1 # E: Not enough arguments for format string '%d %d' % (1, 2) @@ -69,12 +56,6 @@ a = None # type: Any '%W' % 1 # E: Unsupported format character "W" '%b' % 1 # E: Format character "b" is only supported on bytes patterns -[case testStringInterPolationPython2] -# flags: --python-version 2.7 -b'%b' % 1 # E: Format character "b" is only supported in Python 3.5 and later -b'%s' % 1 -b'%a' % 1 # E: Format character "a" is only supported in Python 3 - [case testStringInterpolationWidth] '%2f' % 3.14 '%*f' % 3.14 # E: Not enough arguments for format string @@ -116,18 +97,6 @@ b'%a' % 1 # E: Format character "a" is only supported in Python 3 [builtins fixtures/primitives.pyi] [typing fixtures/typing-medium.pyi] -[case testStringInterPolationCPython2] -# flags: --py2 --no-strict-optional -'%c' % 1 -'%c' % 1.0 # E: "%c" requires int or char (expression has type "float") -'%c' % 's' -'%c' % '' # E: "%c" requires int or char -'%c' % 'ab' # E: "%c" requires int or char -'%c' % b'a' -'%c' % b'' # E: "%c" requires int or char -'%c' % b'ab' # E: "%c" requires int or char -[builtins_py2 fixtures/python2.pyi] - [case testStringInterpolationC] # flags: --python-version 3.6 '%c' % 1 @@ -166,13 +135,6 @@ ds, do, di = None, None, None # type: Dict[str, int], Dict[object, int], Dict[in b'%()d' % ds # E: Format requires a mapping (expression has type "Dict[str, int]", expected type for mapping is "Mapping[bytes, Any]") [builtins fixtures/primitives.pyi] -[case testStringInterpolationMappingInvalidDictTypesPy2] -# flags: --py2 --no-strict-optional -from typing import Any, Dict -di = None # type: Dict[int, int] -'%()d' % di # E: Format requires a mapping (expression has type "Dict[int, int]", expected type for mapping is "Union[Mapping[str, Any], Mapping[unicode, Any]]") -[builtins_py2 fixtures/python2.pyi] - [case testStringInterpolationMappingInvalidSpecifiers] '%(a)d %d' % 1 # E: String interpolation mixes specifier with and without mapping keys '%(b)*d' % 1 # E: String interpolation contains both stars and mapping keys @@ -244,9 +206,6 @@ t5: Iterable[str] = ('A', 'B') '%s %s' % t5 [builtins fixtures/tuple.pyi] -[case testUnicodeInterpolation_python2] -u'%s' % (u'abc',) - -- Bytes interpolation -- -------------------- @@ -261,18 +220,6 @@ b'%b' % 1 # E: Incompatible types in string interpolation (expression has type b'%b' % b'1' b'%a' % 3 -[case testBytesInterPolationCPython2] -# flags: --py2 --no-strict-optional -b'%c' % 1 -b'%c' % 1.0 # E: "%c" requires int or char (expression has type "float") -b'%c' % 's' -b'%c' % '' # E: "%c" requires int or char -b'%c' % 'ab' # E: "%c" requires int or char -b'%c' % b'a' -b'%c' % b'' # E: "%c" requires int or char -b'%c' % b'aa' # E: "%c" requires int or char -[builtins_py2 fixtures/python2.pyi] - [case testBytesInterpolationC] # flags: --python-version 3.6 b'%c' % 1 @@ -522,46 +469,6 @@ class D(bytes): '{}'.format(D()) [builtins fixtures/primitives.pyi] -[case testFormatCallFormatTypesBytesNotPy2] -# flags: --py2 -from typing import Union, TypeVar, NewType, Generic - -A = TypeVar('A', str, unicode) -B = TypeVar('B', bound=str) - -x = '' # type: Union[str, unicode] -a = '' -b = b'' - -N = NewType('N', str) -n = N(b'') - -'{}'.format(a) -'{}'.format(b) -'{}'.format(x) -'{}'.format(n) - -u'{}'.format(a) -u'{}'.format(b) -u'{}'.format(x) -u'{}'.format(n) - -class C(Generic[B]): - x = None # type: B - def meth(self): - # type: () -> None - '{}'.format(self.x) - -def func(x): - # type: (A) -> A - '{}'.format(x) - return x - -'{!r}'.format(b) -'{!r}'.format(x) -'{!r}'.format(n) -[builtins_py2 fixtures/python2.pyi] - [case testFormatCallFinal] from typing_extensions import Final diff --git a/test-data/unit/check-functions.test b/test-data/unit/check-functions.test index dd0ebb96a25b..a91b6099a02e 100644 --- a/test-data/unit/check-functions.test +++ b/test-data/unit/check-functions.test @@ -517,34 +517,6 @@ def f(x: T = B()) -> None: # E: Incompatible default for argument "x" (default h class B: pass class A: pass -[case testDefaultArgumentExpressionsPython2] -# flags: --python-version 2.7 -from typing import Tuple -def f(x = B()): # E: Incompatible default for argument "x" (default has type "B", argument has type "A") - # type: (A) -> None - b = x # type: B # E: Incompatible types in assignment (expression has type "A", variable has type "B") - a = x # type: A - -class B: pass -class A: pass - -[case testDefaultTupleArgumentExpressionsPython2] -# flags: --python-version 2.7 -from typing import Tuple -def f((x, y) = (A(), B())): # E: Incompatible default for tuple argument 1 (default has type "Tuple[A, B]", argument has type "Tuple[B, B]") - # type: (Tuple[B, B]) -> None - b = x # type: B - a = x # type: A # E: Incompatible types in assignment (expression has type "B", variable has type "A") -def g(a, (x, y) = (A(),)): # E: Incompatible default for tuple argument 2 (default has type "Tuple[A]", argument has type "Tuple[B, B]") - # type: (int, Tuple[B, B]) -> None - pass -def h((x, y) = (A(), B(), A())): # E: Incompatible default for tuple argument 1 (default has type "Tuple[A, B, A]", argument has type "Tuple[B, B]") - # type: (Tuple[B, B]) -> None - pass - -class B: pass -class A: pass - [case testDefaultArgumentsWithSubtypes] import typing def f(x: 'B' = A()) -> None: # E: Incompatible default for argument "x" (default has type "A", argument has type "B") @@ -2276,16 +2248,6 @@ a.__eq__(other=a) # E: Unexpected keyword argument "other" for "__eq__" of "A" [builtins fixtures/bool.pyi] -[case testTupleArguments] -# flags: --python-version 2.7 - -def f(a, (b, c), d): pass - -[case testTupleArgumentsFastparse] -# flags: --python-version 2.7 - -def f(a, (b, c), d): pass - -- Type variable shenanagins -- ------------------------- diff --git a/test-data/unit/check-ignore.test b/test-data/unit/check-ignore.test index 048410ecbab7..d304da96ceea 100644 --- a/test-data/unit/check-ignore.test +++ b/test-data/unit/check-ignore.test @@ -246,11 +246,6 @@ IGNORE # type: ignore import MISSING -[case testIgnoreWholeModulePy27] -# flags: --python-version 2.7 -# type: ignore -IGNORE - [case testDontIgnoreWholeModule1] if True: # type: ignore diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test index a7f63d4916df..f094bf36b8c5 100644 --- a/test-data/unit/check-inference.test +++ b/test-data/unit/check-inference.test @@ -3132,13 +3132,6 @@ y['a'] = [] reveal_type(y) # N: Revealed type is "collections.defaultdict[Any, Any]" [builtins fixtures/dict.pyi] -[case testJoinOfStrAndUnicodeSubclass_python2] -class S(unicode): pass -reveal_type(S() if bool() else '') # N: Revealed type is "builtins.unicode" -reveal_type('' if bool() else S()) # N: Revealed type is "builtins.unicode" -reveal_type(S() if bool() else str()) # N: Revealed type is "builtins.unicode" -reveal_type(str() if bool() else S()) # N: Revealed type is "builtins.unicode" - [case testInferCallableReturningNone1] # flags: --no-strict-optional from typing import Callable, TypeVar diff --git a/test-data/unit/check-isinstance.test b/test-data/unit/check-isinstance.test index da6606504343..555e1a568d25 100644 --- a/test-data/unit/check-isinstance.test +++ b/test-data/unit/check-isinstance.test @@ -1988,26 +1988,6 @@ else: [builtins fixtures/dict.pyi] [out] -[case testNarrowTypeAfterInList_python2] -# flags: --strict-optional -from typing import List, Optional - -x = [] # type: List[int] -y = None # type: Optional[int] - -# TODO: Fix running tests on Python 2: "Iterator[int]" has no attribute "next" -if y in x: # type: ignore - reveal_type(y) # N: Revealed type is "builtins.int" -else: - reveal_type(y) # N: Revealed type is "Union[builtins.int, None]" -if y not in x: # type: ignore - reveal_type(y) # N: Revealed type is "Union[builtins.int, None]" -else: - reveal_type(y) # N: Revealed type is "builtins.int" - -[builtins_py2 fixtures/python2.pyi] -[out] - [case testNarrowTypeAfterInNoAnyOrObject] # flags: --strict-optional from typing import Any, List, Optional diff --git a/test-data/unit/check-literal.test b/test-data/unit/check-literal.test index f28e82447e20..5046bd3742b5 100644 --- a/test-data/unit/check-literal.test +++ b/test-data/unit/check-literal.test @@ -48,26 +48,6 @@ y: Literal[43] y = 43 [typing fixtures/typing-medium.pyi] -[case testLiteralParsingPython2] -# flags: --python-version 2.7 -from typing import Optional -from typing_extensions import Literal - -def f(x): # E: Invalid type comment or annotation - # type: ("A[") -> None - pass - -def g(x): - # type: (Literal["A["]) -> None - pass - -x = None # type: Optional[1] # E: Invalid type: try using Literal[1] instead? -y = None # type: Optional[Literal[1]] - -reveal_type(x) # N: Revealed type is "Union[Any, None]" -reveal_type(y) # N: Revealed type is "Union[Literal[1], None]" -[out] - [case testLiteralInsideOtherTypes] from typing import Tuple from typing_extensions import Literal @@ -83,25 +63,6 @@ reveal_type(bar) # N: Revealed type is "def (x: Tuple[Literal [builtins fixtures/tuple.pyi] [out] -[case testLiteralInsideOtherTypesPython2] -# flags: --python-version 2.7 -from typing import Tuple, Optional -from typing_extensions import Literal - -x = None # type: Optional[Tuple[1]] # E: Invalid type: try using Literal[1] instead? -def foo(x): # E: Invalid type: try using Literal[1] instead? - # type: (Tuple[1]) -> None - pass - -y = None # type: Optional[Tuple[Literal[2]]] -def bar(x): - # type: (Tuple[Literal[2]]) -> None - pass -reveal_type(x) # N: Revealed type is "Union[Tuple[Any], None]" -reveal_type(y) # N: Revealed type is "Union[Tuple[Literal[2]], None]" -reveal_type(bar) # N: Revealed type is "def (x: Tuple[Literal[2]])" -[out] - [case testLiteralInsideOtherTypesTypeCommentsPython3] # flags: --python-version 3.7 from typing import Tuple, Optional @@ -188,47 +149,6 @@ reveal_type(expr_com_6) # N: Revealed type is "Literal['"foo"']" [builtins fixtures/bool.pyi] [out] -[case testLiteralValidExpressionsInStringsPython2] -# flags: --python-version=2.7 -from wrapper import * - -[file wrapper.pyi] -from typing_extensions import Literal - -alias_1 = Literal['a+b'] -alias_2 = Literal['1+2'] -alias_3 = Literal['3'] -alias_4 = Literal['True'] -alias_5 = Literal['None'] -alias_6 = Literal['"foo"'] -expr_of_alias_1: alias_1 -expr_of_alias_2: alias_2 -expr_of_alias_3: alias_3 -expr_of_alias_4: alias_4 -expr_of_alias_5: alias_5 -expr_of_alias_6: alias_6 -reveal_type(expr_of_alias_1) # N: Revealed type is "Literal['a+b']" -reveal_type(expr_of_alias_2) # N: Revealed type is "Literal['1+2']" -reveal_type(expr_of_alias_3) # N: Revealed type is "Literal['3']" -reveal_type(expr_of_alias_4) # N: Revealed type is "Literal['True']" -reveal_type(expr_of_alias_5) # N: Revealed type is "Literal['None']" -reveal_type(expr_of_alias_6) # N: Revealed type is "Literal['"foo"']" - -expr_com_1 = ... # type: Literal['a+b'] -expr_com_2 = ... # type: Literal['1+2'] -expr_com_3 = ... # type: Literal['3'] -expr_com_4 = ... # type: Literal['True'] -expr_com_5 = ... # type: Literal['None'] -expr_com_6 = ... # type: Literal['"foo"'] -reveal_type(expr_com_1) # N: Revealed type is "Literal[u'a+b']" -reveal_type(expr_com_2) # N: Revealed type is "Literal[u'1+2']" -reveal_type(expr_com_3) # N: Revealed type is "Literal[u'3']" -reveal_type(expr_com_4) # N: Revealed type is "Literal[u'True']" -reveal_type(expr_com_5) # N: Revealed type is "Literal[u'None']" -reveal_type(expr_com_6) # N: Revealed type is "Literal[u'"foo"']" -[builtins fixtures/bool.pyi] -[out] - [case testLiteralMixingUnicodeAndBytesPython3] from typing_extensions import Literal @@ -293,117 +213,6 @@ accepts_bytes(c_alias) [builtins fixtures/tuple.pyi] [out] -[case testLiteralMixingUnicodeAndBytesPython2] -# flags: --python-version 2.7 -from typing_extensions import Literal - -a_hint = u"foo" # type: Literal[u"foo"] -b_hint = "foo" # type: Literal["foo"] -c_hint = b"foo" # type: Literal[b"foo"] - -AAlias = Literal[u"foo"] -BAlias = Literal["foo"] -CAlias = Literal[b"foo"] -a_alias = u"foo" # type: AAlias -b_alias = "foo" # type: BAlias -c_alias = b"foo" # type: CAlias - -def accepts_unicode(x): - # type: (Literal[u"foo"]) -> None - pass -def accepts_bytes_1(x): - # type: (Literal["foo"]) -> None - pass -def accepts_bytes_2(x): - # type: (Literal[b"foo"]) -> None - pass - -reveal_type(a_hint) # N: Revealed type is "Literal[u'foo']" -reveal_type(b_hint) # N: Revealed type is "Literal['foo']" -reveal_type(c_hint) # N: Revealed type is "Literal['foo']" -reveal_type(a_alias) # N: Revealed type is "Literal[u'foo']" -reveal_type(b_alias) # N: Revealed type is "Literal['foo']" -reveal_type(c_alias) # N: Revealed type is "Literal['foo']" - -accepts_unicode(a_hint) -accepts_unicode(b_hint) # E: Argument 1 to "accepts_unicode" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" -accepts_unicode(c_hint) # E: Argument 1 to "accepts_unicode" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" -accepts_unicode(a_alias) -accepts_unicode(b_alias) # E: Argument 1 to "accepts_unicode" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" -accepts_unicode(c_alias) # E: Argument 1 to "accepts_unicode" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" - -accepts_bytes_1(a_hint) # E: Argument 1 to "accepts_bytes_1" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes_1(b_hint) -accepts_bytes_1(c_hint) -accepts_bytes_1(a_alias) # E: Argument 1 to "accepts_bytes_1" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes_1(b_alias) -accepts_bytes_1(c_alias) - -accepts_bytes_2(a_hint) # E: Argument 1 to "accepts_bytes_2" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes_2(b_hint) -accepts_bytes_2(c_hint) -accepts_bytes_2(a_alias) # E: Argument 1 to "accepts_bytes_2" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes_2(b_alias) -accepts_bytes_2(c_alias) -[builtins fixtures/primitives.pyi] -[out] - -[case testLiteralMixingUnicodeAndBytesPython2UnicodeLiterals] -# flags: --python-version 2.7 -from __future__ import unicode_literals -from typing_extensions import Literal - -a_hint = u"foo" # type: Literal[u"foo"] -b_hint = "foo" # type: Literal["foo"] -c_hint = b"foo" # type: Literal[b"foo"] - -AAlias = Literal[u"foo"] -BAlias = Literal["foo"] -CAlias = Literal[b"foo"] -a_alias = u"foo" # type: AAlias -b_alias = "foo" # type: BAlias -c_alias = b"foo" # type: CAlias - -def accepts_unicode_1(x): - # type: (Literal[u"foo"]) -> None - pass -def accepts_unicode_2(x): - # type: (Literal["foo"]) -> None - pass -def accepts_bytes(x): - # type: (Literal[b"foo"]) -> None - pass - -reveal_type(a_hint) # N: Revealed type is "Literal[u'foo']" -reveal_type(b_hint) # N: Revealed type is "Literal[u'foo']" -reveal_type(c_hint) # N: Revealed type is "Literal['foo']" -reveal_type(a_alias) # N: Revealed type is "Literal[u'foo']" -reveal_type(b_alias) # N: Revealed type is "Literal[u'foo']" -reveal_type(c_alias) # N: Revealed type is "Literal['foo']" - -accepts_unicode_1(a_hint) -accepts_unicode_1(b_hint) -accepts_unicode_1(c_hint) # E: Argument 1 to "accepts_unicode_1" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" -accepts_unicode_1(a_alias) -accepts_unicode_1(b_alias) -accepts_unicode_1(c_alias) # E: Argument 1 to "accepts_unicode_1" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" - -accepts_unicode_2(a_hint) -accepts_unicode_2(b_hint) -accepts_unicode_2(c_hint) # E: Argument 1 to "accepts_unicode_2" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" -accepts_unicode_2(a_alias) -accepts_unicode_2(b_alias) -accepts_unicode_2(c_alias) # E: Argument 1 to "accepts_unicode_2" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" - -accepts_bytes(a_hint) # E: Argument 1 to "accepts_bytes" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes(b_hint) # E: Argument 1 to "accepts_bytes" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes(c_hint) -accepts_bytes(a_alias) # E: Argument 1 to "accepts_bytes" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes(b_alias) # E: Argument 1 to "accepts_bytes" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -accepts_bytes(c_alias) -[builtins fixtures/primitives.pyi] -[out] - [case testLiteralMixingUnicodeAndBytesPython3ForwardStrings] from typing import TypeVar, Generic from typing_extensions import Literal @@ -469,146 +278,6 @@ reveal_type(c_bytes_wrapper_alias) # N: Revealed type is "__main__.Wrap[Liter [builtins fixtures/tuple.pyi] [out] -[case testLiteralMixingUnicodeAndBytesPython2ForwardStrings] -# flags: --python-version 2.7 -from typing import TypeVar, Generic -from typing_extensions import Literal - -T = TypeVar('T') -class Wrap(Generic[T]): pass - -AUnicodeWrapperAlias = Wrap[u"Literal[u'foo']"] -BUnicodeWrapperAlias = Wrap[u"Literal['foo']"] -CUnicodeWrapperAlias = Wrap[u"Literal[b'foo']"] -a_unicode_wrapper_alias = Wrap() # type: AUnicodeWrapperAlias -b_unicode_wrapper_alias = Wrap() # type: BUnicodeWrapperAlias -c_unicode_wrapper_alias = Wrap() # type: CUnicodeWrapperAlias - -AStrWrapperAlias = Wrap["Literal[u'foo']"] -BStrWrapperAlias = Wrap["Literal['foo']"] -CStrWrapperAlias = Wrap["Literal[b'foo']"] -a_str_wrapper_alias = Wrap() # type: AStrWrapperAlias -b_str_wrapper_alias = Wrap() # type: BStrWrapperAlias -c_str_wrapper_alias = Wrap() # type: CStrWrapperAlias - -ABytesWrapperAlias = Wrap[b"Literal[u'foo']"] -BBytesWrapperAlias = Wrap[b"Literal['foo']"] -CBytesWrapperAlias = Wrap[b"Literal[b'foo']"] -a_bytes_wrapper_alias = Wrap() # type: ABytesWrapperAlias -b_bytes_wrapper_alias = Wrap() # type: BBytesWrapperAlias -c_bytes_wrapper_alias = Wrap() # type: CBytesWrapperAlias - -# Unlike Python 3, the exact meaning of Literal['foo'] is "inherited" from the "outer" -# string. For example, the "outer" string is unicode in the first example here. So -# we treat Literal['foo'] as the same as Literal[u'foo']. -reveal_type(a_unicode_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(b_unicode_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(c_unicode_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" - -# However, for both of these examples, the "outer" string is bytes, so we don't treat -# Literal['foo'] as a unicode Literal. -reveal_type(a_str_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(b_str_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" -reveal_type(c_str_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" - -reveal_type(a_bytes_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(b_bytes_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" -reveal_type(c_bytes_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" -[out] - -[case testLiteralMixingUnicodeAndBytesPython2ForwardStringsUnicodeLiterals] -# flags: --python-version 2.7 -from __future__ import unicode_literals -from typing import TypeVar, Generic -from typing_extensions import Literal - -T = TypeVar('T') -class Wrap(Generic[T]): pass - -AUnicodeWrapperAlias = Wrap[u"Literal[u'foo']"] -BUnicodeWrapperAlias = Wrap[u"Literal['foo']"] -CUnicodeWrapperAlias = Wrap[u"Literal[b'foo']"] -a_unicode_wrapper_alias = Wrap() # type: AUnicodeWrapperAlias -b_unicode_wrapper_alias = Wrap() # type: BUnicodeWrapperAlias -c_unicode_wrapper_alias = Wrap() # type: CUnicodeWrapperAlias - -AStrWrapperAlias = Wrap["Literal[u'foo']"] -BStrWrapperAlias = Wrap["Literal['foo']"] -CStrWrapperAlias = Wrap["Literal[b'foo']"] -a_str_wrapper_alias = Wrap() # type: AStrWrapperAlias -b_str_wrapper_alias = Wrap() # type: BStrWrapperAlias -c_str_wrapper_alias = Wrap() # type: CStrWrapperAlias - -ABytesWrapperAlias = Wrap[b"Literal[u'foo']"] -BBytesWrapperAlias = Wrap[b"Literal['foo']"] -CBytesWrapperAlias = Wrap[b"Literal[b'foo']"] -a_bytes_wrapper_alias = Wrap() # type: ABytesWrapperAlias -b_bytes_wrapper_alias = Wrap() # type: BBytesWrapperAlias -c_bytes_wrapper_alias = Wrap() # type: CBytesWrapperAlias - -# This example is almost identical to the previous one, except that we're using -# unicode literals. The first and last examples remain the same, but the middle -# one changes: -reveal_type(a_unicode_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(b_unicode_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(c_unicode_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" - -# Since unicode_literals is enabled, the "outer" string in Wrap["Literal['foo']"] is now -# a unicode string, so we end up treating Literal['foo'] as the same as Literal[u'foo']. -reveal_type(a_str_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(b_str_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(c_str_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" - -reveal_type(a_bytes_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal[u'foo']]" -reveal_type(b_bytes_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" -reveal_type(c_bytes_wrapper_alias) # N: Revealed type is "__main__.Wrap[Literal['foo']]" -[out] - -[case testLiteralMixingUnicodeAndBytesInconsistentUnicodeLiterals] -# flags: --python-version 2.7 -import mod_unicode as u -import mod_bytes as b - -reveal_type(u.func) # N: Revealed type is "def (x: Literal[u'foo'])" -reveal_type(u.var) # N: Revealed type is "Literal[u'foo']" -reveal_type(b.func) # N: Revealed type is "def (x: Literal['foo'])" -reveal_type(b.var) # N: Revealed type is "Literal['foo']" - -from_u = u"foo" # type: u.Alias -from_b = "foo" # type: b.Alias - -u.func(u.var) -u.func(from_u) -u.func(b.var) # E: Argument 1 to "func" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" -u.func(from_b) # E: Argument 1 to "func" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" - -b.func(u.var) # E: Argument 1 to "func" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -b.func(from_u) # E: Argument 1 to "func" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" -b.func(b.var) -b.func(from_b) - -[file mod_unicode.py] -from __future__ import unicode_literals -from typing_extensions import Literal - -def func(x): - # type: (Literal["foo"]) -> None - pass - -Alias = Literal["foo"] -var = "foo" # type: Alias - -[file mod_bytes.py] -from typing_extensions import Literal - -def func(x): - # type: (Literal["foo"]) -> None - pass - -Alias = Literal["foo"] -var = "foo" # type: Alias -[out] - [case testLiteralUnicodeWeirdCharacters] from typing import Any from typing_extensions import Literal @@ -2362,54 +2031,6 @@ del test[bad_keys] # E: Key "a" of TypedDict "Test" cannot be delet [typing fixtures/typing-typeddict.pyi] [out] -[case testLiteralIntelligentIndexingTypedDictPython2-skip] -# flags: --python-version 2.7 -from normal_mod import NormalDict -from unicode_mod import UnicodeDict - -from typing_extensions import Literal - -normal_dict = NormalDict(key=4) -unicode_dict = UnicodeDict(key=4) - -normal_key = "key" # type: Literal["key"] -unicode_key = u"key" # type: Literal[u"key"] - -# TODO: Make the runtime and mypy behaviors here consistent -# -# At runtime, all eight of the below operations will successfully return -# the int because b"key" == u"key" in Python 2. -# -# Mypy, in contrast, will accept all the four calls to `some_dict[...]` -# but will reject `normal_dict.get(unicode_key)` and `unicode_dict.get(unicode_key)` -# because the signature of `.get(...)` accepts only a str, not unicode. -# -# We get the same behavior if we replace all of the Literal[...] types for -# actual string literals. -# -# See https://github.com/python/mypy/issues/6123 for more details. -reveal_type(normal_dict[normal_key]) # N: Revealed type is "builtins.int" -reveal_type(normal_dict[unicode_key]) # N: Revealed type is "builtins.int" -reveal_type(unicode_dict[normal_key]) # N: Revealed type is "builtins.int" -reveal_type(unicode_dict[unicode_key]) # N: Revealed type is "builtins.int" - -reveal_type(normal_dict.get(normal_key)) # N: Revealed type is "builtins.int" -reveal_type(normal_dict.get(unicode_key)) # N: Revealed type is "builtins.int" -reveal_type(unicode_dict.get(normal_key)) # N: Revealed type is "builtins.int" -reveal_type(unicode_dict.get(unicode_key)) # N: Revealed type is "builtins.int" - -[file normal_mod.py] -from mypy_extensions import TypedDict -NormalDict = TypedDict('NormalDict', {'key': int}) - -[file unicode_mod.py] -from __future__ import unicode_literals -from mypy_extensions import TypedDict -UnicodeDict = TypedDict(b'UnicodeDict', {'key': int}) - -[builtins fixtures/dict.pyi] -[typing fixtures/typing-medium.pyi] - [case testLiteralIntelligentIndexingMultiTypedDict] from typing import Union from typing_extensions import Literal @@ -2745,61 +2366,6 @@ force_bytes(reveal_type(c)) # N: Revealed type is "Literal[b'foo']" [builtins fixtures/tuple.pyi] [out] -[case testLiteralFinalStringTypesPython2UnicodeLiterals] -# flags: --python-version 2.7 -from __future__ import unicode_literals -from typing_extensions import Final, Literal - -a = u"foo" # type: Final -b = "foo" # type: Final -c = b"foo" # type: Final - -def force_unicode(x): - # type: (Literal[u"foo"]) -> None - pass -def force_bytes(x): - # type: (Literal[b"foo"]) -> None - pass - -force_unicode(reveal_type(a)) # N: Revealed type is "Literal[u'foo']" -force_unicode(reveal_type(b)) # N: Revealed type is "Literal[u'foo']" -force_unicode(reveal_type(c)) # E: Argument 1 to "force_unicode" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" \ - # N: Revealed type is "Literal['foo']" - -force_bytes(reveal_type(a)) # E: Argument 1 to "force_bytes" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" \ - # N: Revealed type is "Literal[u'foo']" -force_bytes(reveal_type(b)) # E: Argument 1 to "force_bytes" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" \ - # N: Revealed type is "Literal[u'foo']" -force_bytes(reveal_type(c)) # N: Revealed type is "Literal['foo']" -[out] - -[case testLiteralFinalStringTypesPython2] -# flags: --python-version 2.7 -from typing_extensions import Final, Literal - -a = u"foo" # type: Final -b = "foo" # type: Final -c = b"foo" # type: Final - -def force_unicode(x): - # type: (Literal[u"foo"]) -> None - pass -def force_bytes(x): - # type: (Literal[b"foo"]) -> None - pass - -force_unicode(reveal_type(a)) # N: Revealed type is "Literal[u'foo']" -force_unicode(reveal_type(b)) # E: Argument 1 to "force_unicode" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" \ - # N: Revealed type is "Literal['foo']" -force_unicode(reveal_type(c)) # E: Argument 1 to "force_unicode" has incompatible type "Literal['foo']"; expected "Literal[u'foo']" \ - # N: Revealed type is "Literal['foo']" - -force_bytes(reveal_type(a)) # E: Argument 1 to "force_bytes" has incompatible type "Literal[u'foo']"; expected "Literal['foo']" \ - # N: Revealed type is "Literal[u'foo']" -force_bytes(reveal_type(b)) # N: Revealed type is "Literal['foo']" -force_bytes(reveal_type(c)) # N: Revealed type is "Literal['foo']" -[out] - [case testLiteralFinalPropagatesThroughGenerics] from typing import TypeVar, Generic from typing_extensions import Final, Literal diff --git a/test-data/unit/check-modules.test b/test-data/unit/check-modules.test index 6bb803e9c454..60e95877336c 100644 --- a/test-data/unit/check-modules.test +++ b/test-data/unit/check-modules.test @@ -423,20 +423,6 @@ __all__ = [1, 2, 3] [out] main:2: error: Type of __all__ must be "Sequence[str]", not "List[int]" -[case testAllMustBeSequenceStr_python2] -import typing -__all__ = [1, 2, 3] -[builtins_py2 fixtures/module_all_python2.pyi] -[out] -main:2: error: Type of __all__ must be "Sequence[unicode]", not "List[int]" - -[case testAllUnicodeSequenceOK_python2] -import typing -__all__ = [u'a', u'b', u'c'] -[builtins_py2 fixtures/module_all_python2.pyi] - -[out] - [case testUnderscoreExportedValuesInImportAll] import typing from m import * @@ -1306,27 +1292,6 @@ class Sub(x.Base): battr = b'' [out] -[case testImportCycleStability6_python2] -import y -[file x.py] -class Base: - pass -def foo(): - # type: () -> None - import y - i = y.Sub.iattr # type: int - f = y.Sub.fattr # type: float - s = y.Sub.sattr # type: str - u = y.Sub.uattr # type: unicode -[file y.py] -import x -class Sub(x.Base): - iattr = 0 - fattr = 0.0 - sattr = '' - uattr = u'' -[out] - -- This case tests module-level variables. [case testImportCycleStability7] @@ -2957,28 +2922,6 @@ __all__ = ['C'] class C: pass [builtins fixtures/list.pyi] -[case testMypyPathAndPython2Dir_python2] -# flags: --config-file tmp/mypy.ini -from m import f -from mm import g -f(1) -f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int" -g() -g(1) # E: Too many arguments for "g" - -[file xx/@python2/m.pyi] -def f(x: int) -> None: ... - -[file xx/m.pyi] -def f(x: str) -> None: ... - -[file xx/mm.pyi] -def g() -> None: ... - -[file mypy.ini] -\[mypy] -mypy_path = tmp/xx - [case testMypyPathAndPython2Dir] # flags: --config-file tmp/mypy.ini from m import f diff --git a/test-data/unit/check-namedtuple.test b/test-data/unit/check-namedtuple.test index 034889878c37..27ec2c47e053 100644 --- a/test-data/unit/check-namedtuple.test +++ b/test-data/unit/check-namedtuple.test @@ -22,16 +22,6 @@ a, b, c = x # E: Need more than 2 values to unpack (3 expected) x[2] # E: Tuple index out of range [builtins fixtures/tuple.pyi] -[case testNamedTupleUnicode_python2] -from __future__ import unicode_literals -from collections import namedtuple - -# This test is a regression test for a bug where mypyc-compiled mypy -# would crash on namedtuple's with unicode arguments. Our test stubs -# don't actually allow that, though, so we ignore the error and just -# care we don't crash. -X = namedtuple('X', ('x', 'y')) # type: ignore - [case testNamedTupleNoUnderscoreFields] from collections import namedtuple diff --git a/test-data/unit/check-newsemanal.test b/test-data/unit/check-newsemanal.test index 8a163e40b438..163805ab4bcb 100644 --- a/test-data/unit/check-newsemanal.test +++ b/test-data/unit/check-newsemanal.test @@ -1267,33 +1267,6 @@ class Defer: x: str [builtins fixtures/tuple.pyi] -[case testNewAnalyzerMetaclass1_python2] -class A: - __metaclass__ = B - -reveal_type(A.f()) # N: Revealed type is "builtins.int" - -class B(type): - def f(cls): - # type: () -> int - return 0 - -[case testNewAnalyzerMetaclass2_python2] -reveal_type(A.f()) # N: Revealed type is "builtins.int" - -class A: - __metaclass__ = B - -class AA: - __metaclass__ = C # E: Metaclasses not inheriting from "type" are not supported - -class B(type): - def f(cls): - # type: () -> int - return 0 - -class C: pass - [case testNewAnalyzerFinalDefiningModuleVar] from typing import Final diff --git a/test-data/unit/check-overloading.test b/test-data/unit/check-overloading.test index 312d7a6cc7ae..66ac67af1126 100644 --- a/test-data/unit/check-overloading.test +++ b/test-data/unit/check-overloading.test @@ -171,30 +171,6 @@ class A: pass class B: pass [builtins fixtures/isinstance.pyi] -[case testTypeCheckOverloadWithImplementationPy2] -# flags: --python-version 2.7 - -from typing import overload -@overload -def f(x): - # type: (A) -> B - pass - -@overload -def f(x): - # type: (B) -> A - pass - -def f(x): - pass - -reveal_type(f(A())) # N: Revealed type is "__main__.B" -reveal_type(f(B())) # N: Revealed type is "__main__.A" - -class A: pass -class B: pass -[builtins fixtures/isinstance.pyi] - [case testTypeCheckOverloadWithImplementationError] from typing import overload, Any @@ -4017,35 +3993,6 @@ class FakeAttribute(Generic[T]): def dummy(self, instance: T, owner: Type[T]) -> int: ... def dummy(self, instance: Optional[T], owner: Type[T]) -> Union['FakeAttribute[T]', int]: ... -[case testOverloadLambdaUnpackingInference] -# flags: --py2 -from typing import Callable, TypeVar, overload - -T = TypeVar('T') -S = TypeVar('S') - -@overload -def foo(func, item): - # type: (Callable[[T], S], T) -> S - pass - -@overload -def foo(): - # type: () -> None - pass - -def foo(*args): - pass - -def add_proxy(x, y): - # type: (int, str) -> str - pass - -# The lambda definition is a syntax error in Python 3 -tup = (1, '2') -reveal_type(foo(lambda (x, y): add_proxy(x, y), tup)) # N: Revealed type is "builtins.str" -[builtins fixtures/primitives.pyi] - [case testOverloadWithClassMethods] from typing import overload @@ -4610,22 +4557,6 @@ x: Optional[C] reveal_type(rp(x)) # N: Revealed type is "__main__.C" [out] -[case testOptionalIsNotAUnionIfNoStrictOverloadStr] -# flags: -2 --no-strict-optional - -from typing import Optional -from m import relpath -a = '' # type: Optional[str] -reveal_type(relpath(a)) # N: Revealed type is "builtins.str" - -[file m.pyi] -from typing import overload -@overload -def relpath(path: str) -> str: ... -@overload -def relpath(path: unicode) -> unicode: ... -[out] - [case testUnionMathTrickyOverload1] from typing import Union, overload diff --git a/test-data/unit/check-python2.test b/test-data/unit/check-python2.test deleted file mode 100644 index 0481767abd63..000000000000 --- a/test-data/unit/check-python2.test +++ /dev/null @@ -1,444 +0,0 @@ --- Type checker test cases for Python 2.x mode. - - -[case testUnicode] -u = u'foo' -if int(): - u = unicode() -if int(): - s = '' -if int(): - s = u'foo' # E: Incompatible types in assignment (expression has type "unicode", variable has type "str") -if int(): - s = b'foo' -[builtins_py2 fixtures/python2.pyi] - -[case testTypeVariableUnicode] -from typing import TypeVar -T = TypeVar(u'T') - -[case testPrintStatement] -print ''() # E: "str" not callable -print 1, 1() # E: "int" not callable - -[case testPrintStatementWithTarget] -class A: - def write(self, s): - # type: (str) -> None - pass - -class B: - def write(self): - # type: () -> int - pass - -print >>A(), '' -print >>None, '' -print >>1, '' # E: "int" has no attribute "write" -print >>(None + ''), None # E: Unsupported left operand type for + ("None") -print >> B(), '' # E: Argument "file" to "print" has incompatible type "def () -> builtins.int"; expected "def (builtins.str) -> Any" - -[case testDivision] -class A: - def __div__(self, x): - # type: (int) -> str - pass -s = A() / 1 -if int(): - s = '' -if int(): - s = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str") - -[case testStrUnicodeCompatibility] -import typing -def f(x): - # type: (unicode) -> None - pass -f('') -f(u'') -f(b'') -[builtins_py2 fixtures/python2.pyi] - -[case testStaticMethodWithCommentSignature] -class A: - @staticmethod - def f(x): # type: (int) -> str - return '' -A.f(1) -A.f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int" -[builtins_py2 fixtures/staticmethod.pyi] - -[case testRaiseTupleTypeFail] -import typing -x = None # type: typing.Type[typing.Tuple[typing.Any, typing.Any, typing.Any]] -raise x # E: Exception must be derived from BaseException -[builtins_py2 fixtures/exception.pyi] - -[case testRaiseTupleOfThreeOnPython2] -from types import TracebackType -from typing import Optional, Tuple, Type - -e = None # type: Optional[TracebackType] - -# Correct raising several items: - -raise BaseException -raise BaseException(1) -raise (BaseException,) -raise (BaseException(1),) -raise BaseException, 1 -raise BaseException, 1, e -raise BaseException, 1, None - -raise Exception -raise Exception(1) -raise Exception() -raise Exception(1), None -raise Exception(), None -raise Exception(1), None, None -raise Exception(1), None, e -raise (Exception,) -raise (Exception(1),) -raise Exception, 1 -raise Exception, 1, e -raise Exception, 1, None - -# Errors: - -raise int, 1 # E: Argument 1 must be "Type[builtins.BaseException]" subtype -raise int, None # E: Argument 1 must be "Union[builtins.BaseException, Type[builtins.BaseException]]" subtype -raise Exception(1), 1 # E: Argument 1 must be "Type[builtins.BaseException]" subtype -raise Exception(1), 1, None # E: Argument 1 must be "Type[builtins.BaseException]" subtype -raise Exception, 1, 1 # E: Argument 3 must be "Union[types.TracebackType, None]" subtype -raise int, 1, 1 # E: Argument 1 must be "Type[builtins.BaseException]" subtype \ - # E: Argument 3 must be "Union[types.TracebackType, None]" subtype - -# Correct raising tuple: - -t1 = (BaseException,) -t2 = (Exception(1), 2, 3, 4) # type: Tuple[Exception, int, int, int] -t3 = (Exception,) # type: Tuple[Type[Exception], ...] -t4 = (Exception(1),) # type: Tuple[Exception, ...] - -raise t1 -raise t2 -raise t3 -raise t4 - -# Errors: - -raise t1, 1, None # E: Argument 1 must be "Type[builtins.BaseException]" subtype -raise t2, 1 # E: Argument 1 must be "Type[builtins.BaseException]" subtype -raise t3, 1, e # E: Argument 1 must be "Type[builtins.BaseException]" subtype -raise t4, 1, 1 # E: Argument 1 must be "Type[builtins.BaseException]" subtype \ - # E: Argument 3 must be "Union[types.TracebackType, None]" subtype - -w1 = () -w2 = (1, Exception) -w3 = (1,) # type: Tuple[int, ...] - -raise w1 # E: Exception must be derived from BaseException -raise w2 # E: When raising a tuple, first element must by derived from BaseException -raise w3 # E: When raising a tuple, first element must by derived from BaseException - -# Bare raise: - -try: - pass -except Exception: - raise # ok -[builtins_py2 fixtures/exception.pyi] -[file types.pyi] -class TracebackType: pass - -[case testTryExceptWithTuple] -try: - None -except BaseException, e: - e() # E: "BaseException" not callable -[builtins_py2 fixtures/exception.pyi] - -[case testTryExceptUnsupported] -try: - pass -except BaseException, (e, f): # E: Sorry, "except , " is not supported - pass -try: - pass -except BaseException, [e, f, g]: # E: Sorry, "except , " is not supported - pass -try: - pass -except BaseException, e[0]: # E: Sorry, "except , " is not supported - pass -[builtins_py2 fixtures/exception.pyi] - -[case testAlternateNameSuggestions] -class Foo(object): - def say_hello(self): - pass - def say_hell(self): - pass - def say_hullo(self): - pass - def say_goodbye(self): - pass - def go_away(self): - pass - def go_around(self): - pass - def append(self): - pass - def extend(self): - pass - def _add(self): - pass - -f = Foo() -f.say_hallo() # E: "Foo" has no attribute "say_hallo"; maybe "say_hullo", "say_hello", or "say_hell"? -f.go_array() # E: "Foo" has no attribute "go_array"; maybe "go_away"? -f.add() # E: "Foo" has no attribute "add"; maybe "append", "extend", or "_add"? - -[case testTupleArgListDynamicallyTyped] -def f(x, (y, z)): - x = y + z -f(1, 1) -f(1, (1, 2)) - -[case testTupleArgListAnnotated] -from typing import Tuple -def f(x, (y, z)): # type: (object, Tuple[int, str]) -> None - x() # E - y() # E - z() # E -f(object(), (1, '')) -f(1, 1) # E -[builtins_py2 fixtures/tuple.pyi] -[out] -main:3: error: "object" not callable -main:4: error: "int" not callable -main:5: error: "str" not callable -main:7: error: Argument 2 to "f" has incompatible type "int"; expected "Tuple[int, str]" - -[case testNestedTupleArgListAnnotated] -from typing import Tuple -def f(x, (y, (a, b))): # type: (object, Tuple[int, Tuple[str, int]]) -> None - x() # E - y() # E - a() # E - b() # E -f(object(), (1, ('', 2))) -f(1, 1) # E -[builtins fixtures/tuple.pyi] -[out] -main:3: error: "object" not callable -main:4: error: "int" not callable -main:5: error: "str" not callable -main:6: error: "int" not callable -main:8: error: Argument 2 to "f" has incompatible type "int"; expected "Tuple[int, Tuple[str, int]]" - -[case testBackquoteExpr] -`1`.x # E: "str" has no attribute "x" - -[case testImportFromPython2Builtin] -from __builtin__ import int as i -x = 1 # type: i -y = '' # type: i # E: Incompatible types in assignment (expression has type "str", variable has type "int") - -[case testImportPython2Builtin] -import __builtin__ -x = 1 # type: __builtin__.int -y = '' # type: __builtin__.int # E: Incompatible types in assignment (expression has type "str", variable has type "int") - -[case testImportAsPython2Builtin] -import __builtin__ as bi -x = 1 # type: bi.int -y = '' # type: bi.int # E: Incompatible types in assignment (expression has type "str", variable has type "int") - -[case testImportFromPython2BuiltinOverridingDefault] -from __builtin__ import int -x = 1 # type: int -y = '' # type: int # E: Incompatible types in assignment (expression has type "str", variable has type "int") - --- Copied from check-functions.test -[case testEllipsisWithArbitraryArgsOnBareFunctionInPython2] -def f(x, y, z): # type: (...) -> None - pass - --- Copied from check-functions.test -[case testEllipsisWithSomethingAfterItFailsInPython2] -def f(x, y, z): # type: (..., int) -> None - pass -[out] -main:1: error: Ellipses cannot accompany other argument types in function type signature - -[case testLambdaTupleArgInPython2] -f = lambda (x, y): x + y -f((0, 0)) - -def g(): # type: () -> None - pass -reveal_type(lambda (x,): g()) # N: Revealed type is "def (Any)" -[out] - -[case testLambdaTupleArgInferenceInPython2] -from typing import Callable, Tuple - -def f(c): - # type: (Callable[[Tuple[int, int]], int]) -> None - pass -def g(c): - # type: (Callable[[Tuple[int, int]], str]) -> None - pass - -f(lambda (x, y): y) -f(lambda (x, y): x()) # E: "int" not callable -g(lambda (x, y): y) # E: Argument 1 to "g" has incompatible type "Callable[[Tuple[int, int]], int]"; expected "Callable[[Tuple[int, int]], str]" \ - # E: Incompatible return value type (got "int", expected "str") -[out] - -[case testLambdaSingletonTupleArgInPython2] -f = lambda (x,): x + 1 -f((0,)) -[out] - -[case testLambdaNoTupleArgInPython2] -f = lambda (x): x + 1 -f(0) -[out] - -[case testDefTupleEdgeCasesPython2] -def f((x,)): return x -def g((x)): return x -f(0) + g(0) -[out] - -[case testLambdaAsSortKeyForTuplePython2] -from typing import Any, Tuple, Callable -def bar(key): - # type: (Callable[[Tuple[int, int]], int]) -> int - pass -def foo(): - # type: () -> int - return bar(key=lambda (a, b): a) -[out] - -[case testImportBuiltins] - -import __builtin__ -__builtin__.str - -[case testUnicodeAlias] -from typing import List -Alias = List[u'Foo'] -class Foo: pass -[builtins_py2 fixtures/python2.pyi] - -[case testExec] -exec('print 1 + 1') - -[case testUnicodeDocStrings] -# flags: --python-version=2.7 -__doc__ = u"unicode" - -class A: - u"unicode" - -def f(): - # type: () -> None - u"unicode" - -[case testMetaclassBasics] -class M(type): - x = 0 # type: int - def test(cls): - # type: () -> str - return "test" - -class A(object): - __metaclass__ = M - -reveal_type(A.x) # N: Revealed type is "builtins.int" -reveal_type(A.test()) # N: Revealed type is "builtins.str" - -[case testImportedMetaclass] -import m - -class A(object): - __metaclass__ = m.M - -reveal_type(A.x) # N: Revealed type is "builtins.int" -reveal_type(A.test()) # N: Revealed type is "builtins.str" -[file m.py] -class M(type): - x = 0 - def test(cls): - # type: () -> str - return "test" - -[case testDynamicMetaclass] -class C(object): - __metaclass__ = int() # E: Dynamic metaclass not supported for "C" - -[case testMetaclassDefinedAsClass] -class C(object): - class __metaclass__: pass # E: Metaclasses defined as inner classes are not supported - -[case testErrorInMetaclass] -x = 0 -class A(object): - __metaclass__ = m.M # E: Name "m" is not defined -class B(object): - __metaclass__ = M # E: Name "M" is not defined - -[case testMetaclassAndSkippedImportInPython2] -# flags: --ignore-missing-imports -from missing import M -class A(object): - __metaclass__ = M - y = 0 -reveal_type(A.y) # N: Revealed type is "builtins.int" -A.x # E: "Type[A]" has no attribute "x" - -[case testAnyAsBaseOfMetaclass] -from typing import Any, Type -M = None # type: Any -class MM(M): pass -class A(object): - __metaclass__ = MM - -[case testSelfTypeNotSelfType2] -class A: - def g(self): - # type: (None) -> None - pass -[out] -main:2: error: Invalid type for self, or extra argument type in function annotation -main:2: note: (Hint: typically annotations omit the type for self) - -[case testSuper] -class A: - def f(self): # type: () -> None - pass -class B(A): - def g(self): # type: () -> None - super(B, self).f() - super().f() # E: Too few arguments for "super" - -[case testPartialTypeComments_python2] -def foo( - a, # type: str - b, - args=None, -): - # type: (...) -> None - pass - -[case testNoneHasNoBoolInPython2] -none = None -b = none.__bool__() # E: "None" has no attribute "__bool__" - -[case testDictWithoutTypeCommentInPython2] -# flags: --py2 -d = dict() # E: Need type comment for "d" (hint: "d = ... \# type: Dict[, ]") -[builtins_py2 fixtures/floatdict_python2.pyi] diff --git a/test-data/unit/check-reports.test b/test-data/unit/check-reports.test index a6d2c8cfa3fb..423cbcc49289 100644 --- a/test-data/unit/check-reports.test +++ b/test-data/unit/check-reports.test @@ -247,17 +247,6 @@ none_lit 4 2 0 2 0 0 str_lit 4 2 0 2 0 0 true_lit 4 2 0 2 0 0 -[case testLinePrecisionUnicodeLiterals_python2] -# flags: --lineprecision-report out -def f(): # type: () -> object - return u'' -def g(): - return u'' -[outfile out/lineprecision.txt] -Name Lines Precise Imprecise Any Empty Unanalyzed -------------------------------------------------------------- -__main__ 5 2 0 2 1 0 - [case testLinePrecisionIfStatement] # flags: --lineprecision-report out if int(): diff --git a/test-data/unit/check-tuples.test b/test-data/unit/check-tuples.test index fbe0c9f857dd..76bcd2266e62 100644 --- a/test-data/unit/check-tuples.test +++ b/test-data/unit/check-tuples.test @@ -319,36 +319,6 @@ class A: pass class B: pass [builtins fixtures/tuple.pyi] -[case testMultipleAssignmentWithSquareBracketTuplesPython2] -# flags: --python-version 2.7 --no-strict-optional -from typing import Tuple - -def avoid_confusing_test_parser(): - # type: () -> None - t1 = None # type: Tuple[A, B] - t2 = None # type: Tuple[A, B, A] - [a, b] = None, None # type: Tuple[A, B] - [a1, b1] = None, None # type: Tuple[A, B] - - reveal_type(a1) # N: Revealed type is "__main__.A" - reveal_type(b1) # N: Revealed type is "__main__.B" - - if int(): - [a, a] = t1 # E: Incompatible types in assignment (expression has type "B", variable has type "A") - [b, b] = t1 # E: Incompatible types in assignment (expression has type "A", variable has type "B") - [a, b, b] = t2 # E: Incompatible types in assignment (expression has type "A", variable has type "B") - - [a, b] = t1 - [a, b, a1] = t2 - - [a2, b2] = t1 - reveal_type(a2) # N: Revealed type is "__main__.A" - reveal_type(b2) # N: Revealed type is "__main__.B" - -class A: pass -class B: pass -[builtins fixtures/tuple.pyi] - [case testMultipleAssignmentWithInvalidNumberOfValues] from typing import Tuple t1 = None # type: Tuple[A, A, A] @@ -1463,10 +1433,6 @@ x9, y9, x10, y10, z5 = *points2, 1, *points2 # E: Contiguous iterable with same # flags: --python-version 3.6 () = [] -[case testAssignEmptyPy27] -# flags: --python-version 2.7 -() = [] # E: can't assign to () - [case testAssignEmptyBogus] () = 1 # E: "int" object is not iterable [builtins fixtures/tuple.pyi] diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test index 1ca9ec593d11..505d49676a94 100644 --- a/test-data/unit/check-typeddict.test +++ b/test-data/unit/check-typeddict.test @@ -716,15 +716,6 @@ reveal_type(p['x']) # N: Revealed type is "builtins.int" reveal_type(p['y']) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] -[case testCanGetItemOfTypedDictWithValidBytesOrUnicodeLiteralKey] -# flags: --python-version 2.7 -from mypy_extensions import TypedDict -Cell = TypedDict('Cell', {'value': int}) -c = Cell(value=42) -reveal_type(c['value']) # N: Revealed type is "builtins.int" -reveal_type(c[u'value']) # N: Revealed type is "builtins.int" -[builtins_py2 fixtures/dict.pyi] - [case testCannotGetItemOfTypedDictWithInvalidStringLiteralKey] from mypy_extensions import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) @@ -733,12 +724,6 @@ p['typ'] # E: TypedDict "TaggedPoint" has no key "typ" \ # N: Did you mean "type"? [builtins fixtures/dict.pyi] -[case testTypedDictWithUnicodeName] -# flags: --python-version 2.7 -from mypy_extensions import TypedDict -TaggedPoint = TypedDict(u'TaggedPoint', {'type': str, 'x': int, 'y': int}) -[builtins fixtures/dict.pyi] - [case testCannotGetItemOfAnonymousTypedDictWithInvalidStringLiteralKey] from typing import TypeVar from mypy_extensions import TypedDict @@ -1668,15 +1653,6 @@ d = {'x': 1} a.update(d) # E: Argument 1 to "update" of "TypedDict" has incompatible type "Dict[str, int]"; expected "TypedDict({'x'?: int, 'y'?: List[int]})" [builtins fixtures/dict.pyi] -[case testTypedDictNonMappingMethods_python2] -from mypy_extensions import TypedDict -A = TypedDict('A', {'x': int}) -a = A(x=1) -reveal_type(a.copy()) # N: Revealed type is "TypedDict('__main__.A', {'x': builtins.int})" -reveal_type(a.has_key('y')) # N: Revealed type is "builtins.bool" -a.clear() # E: "A" has no attribute "clear" -[builtins_py2 fixtures/dict.pyi] - [case testTypedDictPopMethod] from typing import List from mypy_extensions import TypedDict diff --git a/test-data/unit/check-unreachable-code.test b/test-data/unit/check-unreachable-code.test index ef098c42901e..289d042d8790 100644 --- a/test-data/unit/check-unreachable-code.test +++ b/test-data/unit/check-unreachable-code.test @@ -18,19 +18,6 @@ else: x z = 1 # type: t -[case testConditionalTypeAliasPY3_python2] -import typing -def f(): pass -PY3 = f() -if PY3: - t = int - x = object() + 'x' -else: - t = str - y = 'x' / 1 # E: "str" has no attribute "__div__" -y -z = '' # type: t - [case testConditionalAssignmentPY2] import typing def f(): pass @@ -41,16 +28,6 @@ else: y = 'x' / 1 # E: Unsupported left operand type for / ("str") y -[case testConditionalAssignmentPY2_python2] -import typing -def f(): pass -PY2 = f() -if PY2: - x = object() + 'x' # E: Unsupported left operand type for + ("object") -else: - y = 'x' / 1 -x - [case testConditionalImport] import typing def f(): pass @@ -158,20 +135,6 @@ else: [builtins fixtures/bool.pyi] [out] -[case testSysVersionInfo_python2] -import sys -if sys.version_info[0] >= 3: - def foo(): - # type: () -> int - return 0 -else: - def foo(): - # type: () -> str - return '' -reveal_type(foo()) # N: Revealed type is "builtins.str" -[builtins_py2 fixtures/ops.pyi] -[out] - [case testSysVersionInfo] import sys if sys.version_info[0] >= 3: @@ -182,20 +145,6 @@ reveal_type(foo()) # N: Revealed type is "builtins.int" [builtins fixtures/ops.pyi] [out] -[case testSysVersionInfoNegated_python2] -import sys -if not (sys.version_info[0] < 3): - def foo(): - # type: () -> int - return 0 -else: - def foo(): - # type: () -> str - return '' -reveal_type(foo()) # N: Revealed type is "builtins.str" -[builtins_py2 fixtures/ops.pyi] -[out] - [case testSysVersionInfoReversedOperandsOrder] import sys if (3,) <= sys.version_info: diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index e27dd888c0e3..020f06dbea24 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -130,29 +130,32 @@ two/mod/__init__.py: note: See https://mypy.readthedocs.io/en/stable/running_myp two/mod/__init__.py: note: Common resolutions include: a) using `--exclude` to avoid checking one of them, b) adding `__init__.py` somewhere, c) using `--explicit-package-bases` or adjusting MYPYPATH == Return code: 2 -[case testFlagsFile] +[case testFlagsFile-skip] # cmd: mypy @flagsfile [file flagsfile] --2 +--always-true=FLAG main.py [file main.py] -def f(): - try: - 1/0 - except ZeroDivisionError, err: - print err +# TODO: this test case passes if you try the exact same thing +# outside of the test suite. what's going on? it's not related +# to the extra flags that testcmdline adds. and things work +# in the test suite with py2 (perhaps because it's a +# special option) +x: int +FLAG = False +if not FLAG: + x = "unreachable" [case testConfigFile] # cmd: mypy main.py [file mypy.ini] \[mypy] -python_version = 2.7 +always_true = FLAG [file main.py] -def f(): - try: - 1/0 - except ZeroDivisionError, err: - print err +x: int +FLAG = False +if not FLAG: + x = "unreachable" [case testErrorContextConfig] # cmd: mypy main.py @@ -170,13 +173,12 @@ main.py:2: error: Unsupported operand types for + ("int" and "str") # cmd: mypy --config-file config.ini main.py [file config.ini] \[mypy] -python_version = 2.7 +always_true = FLAG [file main.py] -def f(): - try: - 1/0 - except ZeroDivisionError, err: - print err +x: int +FLAG = False +if not FLAG: + x = "unreachable" [case testNoConfigFile] # cmd: mypy main.py --config-file= @@ -647,6 +649,10 @@ mypy.ini: [mypy]: python_version: Python major version '4' out of range (must be \[mypy] python_version = 2.7 [out] +usage: mypy [-h] [-v] [-V] [more options; see below] + [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...] +mypy: error: Mypy no longer supports checking Python 2 code. Consider pinning to mypy<0.980 if you need to check Python 2 code. +== Return code: 2 [case testPythonVersionAccepted34] # cmd: mypy -c pass diff --git a/test-data/unit/deps-expressions.test b/test-data/unit/deps-expressions.test index 20d727433193..ff8c875b66f0 100644 --- a/test-data/unit/deps-expressions.test +++ b/test-data/unit/deps-expressions.test @@ -375,36 +375,6 @@ def f(a: Union[A, B]) -> int: -> m.f -> , m.B, m.f -[case testBackquoteExpr_python2] -def g(): # type: () -> int - pass -def f(): # type: () -> str - return `g()` -[out] - -> m.f - -[case testComparison_python2] -class A: - def __cmp__(self, other): # type: (B) -> int - pass -class B: - pass - -def f(a, b): # type: (A, B) -> None - x = a == b - -def g(a, b): # type: (A, B) -> None - x = a < b -[out] - -> m.f, m.g - -> m.f - -> m.g - -> , , m.A, m.f, m.g - -> m.f, m.g - -> m.f - -> m.g - -> , , , m.A.__cmp__, m.B, m.f, m.g - [case testSliceExpr] class A: def __getitem__(self, x) -> None: pass diff --git a/test-data/unit/deps-statements.test b/test-data/unit/deps-statements.test index c1099d10ecee..a67f9c762009 100644 --- a/test-data/unit/deps-statements.test +++ b/test-data/unit/deps-statements.test @@ -80,56 +80,6 @@ def g() -> None: -> m.g -> m.g -[case testPrintStmt_python2] -def f1(): # type: () -> int - pass -def f2(): # type: () -> int - pass - -def g1(): # type: () -> None - print f1() - -def g2(): # type: () -> None - print f1(), f2() -[out] - -> m.g1, m.g2 - -> m.g2 - -[case testPrintStmtWithFile_python2] -class A: - def write(self, s): # type: (str) -> None - pass - -def f1(): # type: () -> A - pass -def f2(): # type: () -> int - pass - -def g(): # type: () -> None - print >>f1(), f2() -[out] - -> m.g - -> , m.A, m.f1 - -> m.g - -[case testExecStmt_python2] -def f1(): pass -def f2(): pass -def f3(): pass - -def g1(): # type: () -> None - exec f1() - -def g2(): # type: () -> None - exec f1() in f2() - -def g3(): # type: () -> None - exec f1() in f2(), f3() -[out] - -> m.g1, m.g2, m.g3 - -> m.g2, m.g3 - -> m.g3 - [case testForStmt] from typing import Iterator diff --git a/test-data/unit/deps-types.test b/test-data/unit/deps-types.test index d0674dfadceb..1d7064cde0c7 100644 --- a/test-data/unit/deps-types.test +++ b/test-data/unit/deps-types.test @@ -242,21 +242,6 @@ class M(type): -> , m -> m -[case testMetaclassDepsDeclared_python2] -# flags: --py2 -import mod -class C: - __metaclass__ = mod.M -[file mod.py] -class M(type): - pass -[out] - -> m.C - -> m - -> m - -> , , m - -> m - [case testMetaclassDepsDeclaredNested] import mod @@ -271,47 +256,6 @@ class M(type): -> , m.func -> m, m.func -[case testMetaclassAttributes_python2] -# flags: --py2 -from mod import C -from typing import Type -def f(arg): - # type: (Type[C]) -> None - arg.x -[file mod.py] -class M(type): - x = None # type: int -class C: - __metaclass__ = M -[out] - -> , m.f - -> , m.f - -> m.f - -> , m, m.f - -> m.f - -> m - -[case testMetaclassOperatorsDirect_python2] -# flags: --py2 -from mod import C -def f(): - # type: () -> None - C + C -[file mod.py] -class M(type): - def __add__(self, other): - # type: (M) -> M - pass -class C: - __metaclass__ = M -[out] - -> m.f - -> m.f - -> m, m.f - -> m.f - -> m.f - -> m - -- Type aliases [case testAliasDepsNormalMod] diff --git a/test-data/unit/deps.test b/test-data/unit/deps.test index 884b10f166b0..0714940246e5 100644 --- a/test-data/unit/deps.test +++ b/test-data/unit/deps.test @@ -1122,29 +1122,6 @@ def f() -> None: -> , , m.A.__iter__, m.B, m.B.__iter__ -> , m.B.__next__, m.C -[case testCustomIterator_python2] -class A: - def __iter__(self): # type: () -> B - pass -class B: - def __iter__(self): # type: () -> B - pass - def next(self): # type: () -> C - pass -class C: - pass -def f(): # type: () -> None - for x in A(): pass -[out] - -> m.f - -> m.f - -> m.f - -> m.f - -> m.A, m.f - -> m.f - -> , , m.A.__iter__, m.B, m.B.__iter__ - -> , m.B.next, m.C - [case testDepsLiskovClass] from mod import A, C class D(C): @@ -1386,40 +1363,6 @@ def h() -> None: -> m.h -> m.D, m.h -[case testLogicalSuperPython2] -# flags: --logical-deps --py2 -class A: - def __init__(self): - pass - def m(self): - pass -class B(A): - def m(self): - pass -class C(B): - pass -class D(C): - def __init__(self): - # type: () -> None - super(B, self).__init__() - def mm(self): - # type: () -> None - super(B, self).m() -[out] - -> m.D.__init__ - -> , m.B.m - -> m.D.mm - -> m, m.A, m.B - -> m.D.__init__ - -> m.D.mm - -> m.D.mm - -> m, m.B, m.C - -> m.D.__init__ - -> m.D.mm - -> m.D.mm - -> m, m.C, m.D - -> m.D - [case testDataclassDepsOldVersion] # flags: --python-version 3.7 from dataclasses import dataclass diff --git a/test-data/unit/fine-grained-blockers.test b/test-data/unit/fine-grained-blockers.test index 45de0013616d..f3991c0d31e4 100644 --- a/test-data/unit/fine-grained-blockers.test +++ b/test-data/unit/fine-grained-blockers.test @@ -563,26 +563,6 @@ mypy: can't decode file 'tmp/a.py': 'ascii' codec can't decode byte 0xc3 in posi == main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" -[case testDecodeErrorBlocker_python2-only_when_nocache] -# flags: --py2 -import a -a.f(1) -[file a.py] -def f(x): - # type: (int) -> None - pass -[file a.py.2] -รค = 1 -[file a.py.3] -def f(x): - # type: (str) -> None - pass -[out] -== -mypy: can't decode file 'tmp/a.py': 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) -== -main:3: error: Argument 1 to "f" has incompatible type "int"; expected "str" - [case testDecodeErrorBlockerOnInitialRun-posix] # Note that there's no test variant for Windows, since the above Windows test case is good enough. import a diff --git a/test-data/unit/fine-grained-modules.test b/test-data/unit/fine-grained-modules.test index 80a2883ee756..19c1242c7d51 100644 --- a/test-data/unit/fine-grained-modules.test +++ b/test-data/unit/fine-grained-modules.test @@ -2159,7 +2159,7 @@ main.py:2: error: Incompatible types in assignment (expression has type "int", v == [case testMissingStubAdded2] -# flags: --follow-imports=skip --py2 +# flags: --follow-imports=skip # cmd: mypy main.py [file main.py] diff --git a/test-data/unit/fine-grained-suggest.test b/test-data/unit/fine-grained-suggest.test index 4a1bda8b0afd..a28e3204b93f 100644 --- a/test-data/unit/fine-grained-suggest.test +++ b/test-data/unit/fine-grained-suggest.test @@ -221,19 +221,6 @@ Foo('lol') (str) -> None == -[case testSuggestTryText] -# flags: --py2 -# suggest: --try-text foo.foo -[file foo.py] -def foo(s): - return s -[file bar.py] -from foo import foo -foo('lol') -[out] -(Text) -> Text -== - [case testSuggestInferMethod1] # flags: --strict-optional # suggest: --no-any foo.Foo.foo diff --git a/test-data/unit/fine-grained.test b/test-data/unit/fine-grained.test index f58cad116bb6..4a1dc5cc93c7 100644 --- a/test-data/unit/fine-grained.test +++ b/test-data/unit/fine-grained.test @@ -2619,21 +2619,6 @@ class C(Generic[T]): pass main:3: error: "C" expects 2 type arguments, but 1 given == -[case testPrintStatement_python2] -# flags: --py2 -import a -[file a.py] -def f(x): # type: (int) -> int - return 1 -print f(1) -[file a.py.2] -def f(x): # type: (int) -> int - return 1 -print f('') -[out] -== -a.py:3: error: Argument 1 to "f" has incompatible type "str"; expected "int" - [case testUnannotatedClass] import a [file a.py] @@ -2836,21 +2821,6 @@ a.py:3: error: "int" not callable == a.py:3: error: "int" not callable -[case testMetaclassDefinition_python2] -# flags: --py2 -import abc -import m -m.f() - -class A: - __metaclass__ = abc.ABCMeta -[file m.py] -def f(): pass -[file m.py.2] -def f(x=1): pass -[out] -== - [case testMetaclassAttributes] import a [file a.py] @@ -2955,64 +2925,6 @@ class M(type): a.py:3: error: Unsupported operand types for + ("Type[C]" and "Type[C]") == -[case testMetaclassAttributesDirect_python2] -# flags: --py2 -import a -[file a.py] -from mod import C -def f(): - # type: () -> None - C.x = int() -[file mod.py] -import submod -class C: - __metaclass__ = submod.M -[file submod.py] -class M(type): - x = None # type: int -[file submod.py.2] -class M(type): - x = None # type: str -[file submod.py.3] -class M(type): - y = None # type: str -[file submod.py.4] -class M(type): - x = None # type: int -[out] -== -a.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "str") -== -a.py:4: error: "Type[C]" has no attribute "x" -== - -[case testMetaclassOperators_python2] -# flags: --py2 -import a -[file a.py] -from mod import C -from typing import Type -def f(arg): - # type: (Type[C]) -> None - arg + arg -[file mod.py] -import submod -class C: - __metaclass__ = submod.M -[file submod.py] -class M(type): - def __add__(self, other): - # type: (M) -> M - pass -[file submod.py.2] -class M(type): - def __add__(self, other): - # type: (int) -> M - pass -[out] -== -a.py:5: error: Unsupported operand types for + ("Type[C]" and "Type[C]") - [case testFineMetaclassUpdate] import a [file a.py] @@ -8086,70 +7998,6 @@ Func = Callable[..., Any] [out] == -[case testIdLikeDecoForwardCrash_python2] -# flags: --py2 -import b -[file b.py] -from typing import Callable, Any, TypeVar - -F = TypeVar('F_BadName', bound=Callable[..., Any]) # type: ignore -def deco(func): # type: ignore - # type: (F) -> F - pass - -@deco -def test(x, y): - # type: (int, int) -> str - pass -[file b.py.2] -from typing import Callable, Any, TypeVar - -F = TypeVar('F_BadName', bound=Callable[..., Any]) # type: ignore -def deco(func): # type: ignore - # type: (F) -> F - pass - -@deco -def test(x, y): - # type: (int, int) -> str - pass -x = 1 -[out] -== - -[case testIdLikeDecoForwardCrashAlias_python2] -# flags: --py2 -import b -[file b.py] -from typing import Callable, Any, TypeVar - -F = TypeVar('F', bound=Func) -def deco(func): - # type: (F) -> F - pass - -@deco -def test(x, y): - # type: (int, int) -> str - pass -Func = Callable[..., Any] -[file b.py.2] -from typing import Callable, Any, TypeVar - -F = TypeVar('F', bound=Func) -def deco(func): - # type: (F) -> F - pass - -@deco -def test(x, y): - # type: (int, int) -> str - pass -x = 1 -Func = Callable[..., Any] -[out] -== - -- Test cases for final qualifier [case testFinalAddFinalVarAssignFine] @@ -8819,51 +8667,6 @@ main:2: note: Revealed type is "Literal['foo']" == main:2: note: Revealed type is "Literal[b'foo']" -[case testLiteralFineGrainedStringConversionPython2] -# flags: --python-version 2.7 -from mod1 import foo -reveal_type(foo) -[file mod1.py] -from mod2 import bar -foo = bar() -[file mod2.py] -from typing_extensions import Literal -def bar(): - # type: () -> Literal["foo"] - pass -[file mod2.py.2] -from typing_extensions import Literal -def bar(): - # type: () -> Literal[b"foo"] - pass -[file mod2.py.3] -from __future__ import unicode_literals -from typing_extensions import Literal -def bar(): - # type: () -> Literal["foo"] - pass -[file mod2.py.4] -from __future__ import unicode_literals -from typing_extensions import Literal -def bar(): - # type: () -> Literal[b"foo"] - pass -[file mod2.py.5] -from typing_extensions import Literal -def bar(): - # type: () -> Literal[u"foo"] - pass -[out] -main:3: note: Revealed type is "Literal['foo']" -== -main:3: note: Revealed type is "Literal['foo']" -== -main:3: note: Revealed type is "Literal[u'foo']" -== -main:3: note: Revealed type is "Literal['foo']" -== -main:3: note: Revealed type is "Literal[u'foo']" - [case testReprocessModuleTopLevelWhileMethodDefinesAttr] import a [file a.py] diff --git a/test-data/unit/parse-python2.test b/test-data/unit/parse-python2.test deleted file mode 100644 index e0bcdf286281..000000000000 --- a/test-data/unit/parse-python2.test +++ /dev/null @@ -1,809 +0,0 @@ --- Test cases for parser -- Python 2 syntax. --- --- See parse.test for a description of this file format. - -[case testEmptyFile] -[out] -MypyFile:1() - -[case testStringLiterals] -'bar' -u'foo' -ur'foo' -u'''bar''' -b'foo' -[out] -MypyFile:1( - ExpressionStmt:1( - StrExpr(bar)) - ExpressionStmt:2( - UnicodeExpr(foo)) - ExpressionStmt:3( - UnicodeExpr(foo)) - ExpressionStmt:4( - UnicodeExpr(bar)) - ExpressionStmt:5( - StrExpr(foo))) - -[case testSimplePrint] -print 1 -print 2, 3 -print (4, 5) -[out] -MypyFile:1( - PrintStmt:1( - IntExpr(1) - Newline) - PrintStmt:2( - IntExpr(2) - IntExpr(3) - Newline) - PrintStmt:3( - TupleExpr:3( - IntExpr(4) - IntExpr(5)) - Newline)) - -[case testPrintWithNoArgs] -print -[out] -MypyFile:1( - PrintStmt:1( - Newline)) - -[case testPrintWithTarget] -print >>foo -[out] -MypyFile:1( - PrintStmt:1( - Target( - NameExpr(foo)) - Newline)) - -[case testPrintWithTargetAndArgs] -print >>foo, x -[out] -MypyFile:1( - PrintStmt:1( - NameExpr(x) - Target( - NameExpr(foo)) - Newline)) - -[case testPrintWithTargetAndArgsAndTrailingComma] -print >>foo, x, y, -[out] -MypyFile:1( - PrintStmt:1( - NameExpr(x) - NameExpr(y) - Target( - NameExpr(foo)))) - -[case testSimpleWithTrailingComma] -print 1, -print 2, 3, -print (4, 5), -[out] -MypyFile:1( - PrintStmt:1( - IntExpr(1)) - PrintStmt:2( - IntExpr(2) - IntExpr(3)) - PrintStmt:3( - TupleExpr:3( - IntExpr(4) - IntExpr(5)))) - -[case testOctalIntLiteral] -00 -01 -0377 -[out] -MypyFile:1( - ExpressionStmt:1( - IntExpr(0)) - ExpressionStmt:2( - IntExpr(1)) - ExpressionStmt:3( - IntExpr(255))) - -[case testLongLiteral] -0L -123L -012L -0x123l -[out] -MypyFile:1( - ExpressionStmt:1( - IntExpr(0)) - ExpressionStmt:2( - IntExpr(123)) - ExpressionStmt:3( - IntExpr(10)) - ExpressionStmt:4( - IntExpr(291))) - -[case testTryExceptWithComma] -try: - x -except Exception, e: - y -[out] -MypyFile:1( - TryStmt:1( - Block:1( - ExpressionStmt:2( - NameExpr(x))) - NameExpr(Exception) - NameExpr(e) - Block:3( - ExpressionStmt:4( - NameExpr(y))))) - -[case testTryExceptWithNestedComma] -try: - x -except (KeyError, IndexError): - y -[out] -MypyFile:1( - TryStmt:1( - Block:1( - ExpressionStmt:2( - NameExpr(x))) - TupleExpr:3( - NameExpr(KeyError) - NameExpr(IndexError)) - Block:3( - ExpressionStmt:4( - NameExpr(y))))) - -[case testExecStatement] -exec a -[out] -MypyFile:1( - ExecStmt:1( - NameExpr(a))) - -[case testExecStatementWithIn] -exec a in globals() -[out] -MypyFile:1( - ExecStmt:1( - NameExpr(a) - CallExpr:1( - NameExpr(globals) - Args()))) - -[case testExecStatementWithInAnd2Expressions] -exec a in x, y -[out] -MypyFile:1( - ExecStmt:1( - NameExpr(a) - NameExpr(x) - NameExpr(y))) - -[case testEllipsisInExpression_python2] -x = ... # E: invalid syntax -[out] - -[case testStrLiteralConcatenationWithMixedLiteralTypes] -u'foo' 'bar' -'bar' u'foo' -[out] -MypyFile:1( - ExpressionStmt:1( - UnicodeExpr(foobar)) - ExpressionStmt:2( - UnicodeExpr(barfoo))) - -[case testLegacyInequality] -1 <> 2 -[out] -MypyFile:1( - ExpressionStmt:1( - ComparisonExpr:1( - != - IntExpr(1) - IntExpr(2)))) - -[case testListComprehensionInPython2] -([ 0 for x in 1, 2 if 3 ]) -[out] -MypyFile:1( - ExpressionStmt:1( - ListComprehension:1( - GeneratorExpr:1( - IntExpr(0) - NameExpr(x) - TupleExpr:1( - IntExpr(1) - IntExpr(2)) - IntExpr(3))))) - -[case testTupleArgListInPython2] -def f(x, (y, z)): pass -[out] -MypyFile:1( - FuncDef:1( - f - Args( - Var(x) - Var(__tuple_arg_2)) - Block:1( - AssignmentStmt:1( - TupleExpr:1( - NameExpr(y) - NameExpr(z)) - NameExpr(__tuple_arg_2)) - PassStmt:1()))) - -[case testTupleArgListWithTwoTupleArgsInPython2] -def f((x, y), (z, zz)): pass -[out] -MypyFile:1( - FuncDef:1( - f - Args( - Var(__tuple_arg_1) - Var(__tuple_arg_2)) - Block:1( - AssignmentStmt:1( - TupleExpr:1( - NameExpr(x) - NameExpr(y)) - NameExpr(__tuple_arg_1)) - AssignmentStmt:1( - TupleExpr:1( - NameExpr(z) - NameExpr(zz)) - NameExpr(__tuple_arg_2)) - PassStmt:1()))) - -[case testTupleArgListWithInitializerInPython2] -def f((y, z) = (1, 2)): pass -[out] -MypyFile:1( - FuncDef:1( - f - Args( - default( - Var(__tuple_arg_1) - TupleExpr:1( - IntExpr(1) - IntExpr(2)))) - Block:1( - AssignmentStmt:1( - TupleExpr:1( - NameExpr(y) - NameExpr(z)) - NameExpr(__tuple_arg_1)) - PassStmt:1()))) - -[case testLambdaTupleArgListInPython2] -lambda (x, y): z -[out] -MypyFile:1( - ExpressionStmt:1( - LambdaExpr:1( - Args( - Var(__tuple_arg_1)) - Block:1( - AssignmentStmt:1( - TupleExpr:1( - NameExpr(x) - NameExpr(y)) - NameExpr(__tuple_arg_1)) - ReturnStmt:1( - NameExpr(z)))))) - -[case testLambdaSingletonTupleArgListInPython2] -lambda (x,): z -[out] -MypyFile:1( - ExpressionStmt:1( - LambdaExpr:1( - Args( - Var(__tuple_arg_1)) - Block:1( - AssignmentStmt:1( - TupleExpr:1( - NameExpr(x)) - NameExpr(__tuple_arg_1)) - ReturnStmt:1( - NameExpr(z)))))) - -[case testLambdaNoTupleArgListInPython2] -lambda (x): z -[out] -MypyFile:1( - ExpressionStmt:1( - LambdaExpr:1( - Args( - Var(x)) - Block:1( - ReturnStmt:1( - NameExpr(z)))))) - -[case testInvalidExprInTupleArgListInPython2_1] -def f(x, ()): pass -[out] -main:1: error: invalid syntax - -[case testInvalidExprInTupleArgListInPython2_2] -def f(x, (y, x[1])): pass -[out] -main:1: error: invalid syntax - -[case testListLiteralAsTupleArgInPython2] -def f(x, [x]): pass -[out] -main:1: error: invalid syntax - -[case testTupleArgAfterStarArgInPython2] -def f(*a, (b, c)): pass -[out] -main:1: error: invalid syntax - -[case testTupleArgAfterStarStarArgInPython2] -def f(*a, (b, c)): pass -[out] -main:1: error: invalid syntax - -[case testParenthesizedArgumentInPython2] -def f(x, (y)): pass -[out] -MypyFile:1( - FuncDef:1( - f - Args( - Var(x) - Var(y)) - Block:1( - PassStmt:1()))) - -[case testDuplicateNameInTupleArgList_python2] -def f(a, (a, b)): - pass -def g((x, (x, y))): - pass -[out] -main:1: error: Duplicate argument "a" in function definition -main:3: error: Duplicate argument "x" in function definition - -[case testBackquotesInPython2] -`1 + 2` -[out] -MypyFile:1( - ExpressionStmt:1( - BackquoteExpr:1( - OpExpr:1( - + - IntExpr(1) - IntExpr(2))))) - -[case testBackquoteSpecialCasesInPython2] -`1, 2` -[out] -MypyFile:1( - ExpressionStmt:1( - BackquoteExpr:1( - TupleExpr:1( - IntExpr(1) - IntExpr(2))))) - -[case testSuperInPython2] -class A: - def f(self): - super(A, self).x -[out] -MypyFile:1( - ClassDef:1( - A - FuncDef:2( - f - Args( - Var(self)) - Block:2( - ExpressionStmt:3( - SuperExpr:3( - x - CallExpr:3( - NameExpr(super) - Args( - NameExpr(A) - NameExpr(self))))))))) - -[case testTypeCommentsInPython2] -x = 1 # type: List[int] - -def f(x, y=0): - # type: (List[int], str) -> None - pass -[out] -MypyFile:1( - AssignmentStmt:1( - NameExpr(x) - IntExpr(1) - List?[int?]) - FuncDef:3( - f - Args( - Var(x) - default( - Var(y) - IntExpr(0))) - def (x: List?[int?], y: str? =) -> None? - Block:3( - PassStmt:5()))) - -[case testMultiLineTypeCommentInPython2] -def f(x, # type: List[int] - y, - z=1, # type: str - ): - # type: (...) -> None - pass -[out] -MypyFile:1( - FuncDef:1( - f - Args( - Var(x) - Var(y) - default( - Var(z) - IntExpr(1))) - def (x: List?[int?], y: Any, z: str? =) -> None? - Block:1( - PassStmt:6()))) - -[case testIfStmtInPython2] -if x: - y -elif z: - a -else: - b -[out] -MypyFile:1( - IfStmt:1( - If( - NameExpr(x)) - Then( - ExpressionStmt:2( - NameExpr(y))) - Else( - IfStmt:3( - If( - NameExpr(z)) - Then( - ExpressionStmt:4( - NameExpr(a))) - Else( - ExpressionStmt:6( - NameExpr(b))))))) - -[case testWhileStmtInPython2] -while x: - y -else: - z -[out] -MypyFile:1( - WhileStmt:1( - NameExpr(x) - Block:1( - ExpressionStmt:2( - NameExpr(y))) - Else( - ExpressionStmt:4( - NameExpr(z))))) - -[case testForStmtInPython2] -for x, y in z: - a -else: - b -[out] -MypyFile:1( - ForStmt:1( - TupleExpr:1( - NameExpr(x) - NameExpr(y)) - NameExpr(z) - Block:1( - ExpressionStmt:2( - NameExpr(a))) - Else( - ExpressionStmt:4( - NameExpr(b))))) - -[case testWithStmtInPython2] -with x as y: - z -[out] -MypyFile:1( - WithStmt:1( - Expr( - NameExpr(x)) - Target( - NameExpr(y)) - Block:1( - ExpressionStmt:2( - NameExpr(z))))) - -[case testExpressionsInPython2] -x[y] -x + y -~z -x.y -([x, y]) -{x, y} -{x: y} -x < y > z -[out] -MypyFile:1( - ExpressionStmt:1( - IndexExpr:1( - NameExpr(x) - NameExpr(y))) - ExpressionStmt:2( - OpExpr:2( - + - NameExpr(x) - NameExpr(y))) - ExpressionStmt:3( - UnaryExpr:3( - ~ - NameExpr(z))) - ExpressionStmt:4( - MemberExpr:4( - NameExpr(x) - y)) - ExpressionStmt:5( - ListExpr:5( - NameExpr(x) - NameExpr(y))) - ExpressionStmt:6( - SetExpr:6( - NameExpr(x) - NameExpr(y))) - ExpressionStmt:7( - DictExpr:7( - NameExpr(x) - NameExpr(y))) - ExpressionStmt:8( - ComparisonExpr:8( - < - > - NameExpr(x) - NameExpr(y) - NameExpr(z)))) - -[case testSlicingInPython2] -x[y:] -x[y:z] -x[::y] -[out] -MypyFile:1( - ExpressionStmt:1( - IndexExpr:1( - NameExpr(x) - SliceExpr:1( - NameExpr(y) - ))) - ExpressionStmt:2( - IndexExpr:2( - NameExpr(x) - SliceExpr:2( - NameExpr(y) - NameExpr(z)))) - ExpressionStmt:3( - IndexExpr:3( - NameExpr(x) - SliceExpr:3( - - - NameExpr(y))))) - -[case testStarArgsInPython2] -def f(*x): # type: (*int) -> None - pass -f(x, *y) -[out] -MypyFile:1( - FuncDef:1( - f - def (*x: int?) -> None? - VarArg( - Var(x)) - Block:1( - PassStmt:2())) - ExpressionStmt:3( - CallExpr:3( - NameExpr(f) - Args( - NameExpr(x) - NameExpr(y)) - VarArg))) - -[case testKwArgsInPython2] -def f(**x): # type: (**int) -> None - pass -f(x, **y) -[out] -MypyFile:1( - FuncDef:1( - f - def (**x: int?) -> None? - DictVarArg( - Var(x)) - Block:1( - PassStmt:2())) - ExpressionStmt:3( - CallExpr:3( - NameExpr(f) - Args( - NameExpr(x)) - DictVarArg( - NameExpr(y))))) - -[case testBoolOpInPython2] -x and y or z -[out] -MypyFile:1( - ExpressionStmt:1( - OpExpr:1( - or - OpExpr:1( - and - NameExpr(x) - NameExpr(y)) - NameExpr(z)))) - -[case testImportsInPython2] -from x import y, z as zz -import m -import n as nn -from aa import * -[out] -MypyFile:1( - ImportFrom:1(x, [y, z : zz]) - Import:2(m) - Import:3(n : nn) - ImportAll:4(aa)) - -[case testTryFinallyInPython2] -try: - x -finally: - y -[out] -MypyFile:1( - TryStmt:1( - Block:1( - ExpressionStmt:2( - NameExpr(x))) - Finally( - ExpressionStmt:4( - NameExpr(y))))) - -[case testRaiseInPython2] -raise -raise x -[out] -MypyFile:1( - RaiseStmt:1() - RaiseStmt:2( - NameExpr(x))) - -[case testAssignmentInPython2] -x = y -x, (y, z) = aa -[out] -MypyFile:1( - AssignmentStmt:1( - NameExpr(x) - NameExpr(y)) - AssignmentStmt:2( - TupleExpr:2( - NameExpr(x) - TupleExpr:2( - NameExpr(y) - NameExpr(z))) - NameExpr(aa))) - -[case testAugmentedAssignmentInPython2] -x += y -x *= 2 -[out] -MypyFile:1( - OperatorAssignmentStmt:1( - + - NameExpr(x) - NameExpr(y)) - OperatorAssignmentStmt:2( - * - NameExpr(x) - IntExpr(2))) - -[case testDelStatementInPython2] -del x -del x.y, x[y] -[out] -MypyFile:1( - DelStmt:1( - NameExpr(x)) - DelStmt:2( - TupleExpr:2( - MemberExpr:2( - NameExpr(x) - y) - IndexExpr:2( - NameExpr(x) - NameExpr(y))))) - -[case testClassDecoratorInPython2] -@dec() -class C: - pass -[out] -MypyFile:1( - ClassDef:2( - C - Decorators( - CallExpr:1( - NameExpr(dec) - Args())) - PassStmt:3())) - -[case testFunctionDecaratorInPython2] -@dec() -def f(): - pass -[out] -MypyFile:1( - Decorator:1( - Var(f) - CallExpr:1( - NameExpr(dec) - Args()) - FuncDef:2( - f - Block:2( - PassStmt:3())))) - -[case testOverloadedFunctionInPython2] -@overload -def g(): - pass -@overload -def g(): - pass -def g(): - pass -[out] -MypyFile:1( - OverloadedFuncDef:1( - Decorator:1( - Var(g) - NameExpr(overload) - FuncDef:2( - g - Block:2( - PassStmt:3()))) - Decorator:4( - Var(g) - NameExpr(overload) - FuncDef:5( - g - Block:5( - PassStmt:6()))) - FuncDef:7( - g - Block:7( - PassStmt:8())))) diff --git a/test-data/unit/python2eval.test b/test-data/unit/python2eval.test deleted file mode 100644 index d9fb729ff3be..000000000000 --- a/test-data/unit/python2eval.test +++ /dev/null @@ -1,449 +0,0 @@ --- 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" diff --git a/test-data/unit/semanal-python2.test b/test-data/unit/semanal-python2.test deleted file mode 100644 index 8bb0f5cf5d9c..000000000000 --- a/test-data/unit/semanal-python2.test +++ /dev/null @@ -1,76 +0,0 @@ --- Python 2 semantic analysis test cases. - -[case testPrintStatement_python2] -print int, None -[out] -MypyFile:1( - PrintStmt:1( - NameExpr(int [builtins.int]) - NameExpr(None [builtins.None]) - Newline)) - -[case testPrintStatementWithTarget] -print >>int, None -[out] -MypyFile:1( - PrintStmt:1( - NameExpr(None [builtins.None]) - Target( - NameExpr(int [builtins.int])) - Newline)) - -[case testExecStatement] -exec None -exec None in int -exec None in int, str -[out] -MypyFile:1( - ExecStmt:1( - NameExpr(None [builtins.None])) - ExecStmt:2( - NameExpr(None [builtins.None]) - NameExpr(int [builtins.int])) - ExecStmt:3( - NameExpr(None [builtins.None]) - NameExpr(int [builtins.int]) - NameExpr(str [builtins.str]))) - -[case testVariableLengthTuple_python2] -from typing import Tuple, cast -cast(Tuple[int, ...], ()) -[builtins_py2 fixtures/tuple.pyi] -[out] -MypyFile:1( - ImportFrom:1(typing, [Tuple, cast]) - ExpressionStmt:2( - CastExpr:2( - TupleExpr:2() - builtins.tuple[builtins.int, ...]))) - -[case testTupleArgList_python2] -def f(x, (y, z)): - x = y -[out] -MypyFile:1( - FuncDef:1( - f - Args( - Var(x) - Var(__tuple_arg_2)) - Block:1( - AssignmentStmt:1( - TupleExpr:1( - NameExpr(y* [l]) - NameExpr(z* [l])) - NameExpr(__tuple_arg_2 [l])) - AssignmentStmt:2( - NameExpr(x [l]) - NameExpr(y [l]))))) - -[case testBackquoteExpr_python2] -`object` -[out] -MypyFile:1( - ExpressionStmt:1( - BackquoteExpr:1( - NameExpr(object [builtins.object]))))