Skip to content

Commit

Permalink
[stubtest] Test NamedTuple definitions with default fields (#15774)
Browse files Browse the repository at this point in the history
This is a test case for #15680 from
`stubtest`'s point of view.
  • Loading branch information
sobolevn authored Jul 29, 2023
1 parent da1853f commit 14efdf2
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions mypy/test/teststubtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class Mapping(Generic[_K, _V]): ...
class Match(Generic[AnyStr]): ...
class Sequence(Iterable[_T_co]): ...
class Tuple(Sequence[_T_co]): ...
class NamedTuple(tuple[Any, ...]): ...
def overload(func: _T) -> _T: ...
"""

Expand All @@ -82,6 +83,7 @@ def overload(func: _T) -> _T: ...
class object:
__module__: str
def __init__(self) -> None: pass
def __repr__(self) -> str: pass
class type: ...
class tuple(Sequence[T_co], Generic[T_co]): ...
Expand Down Expand Up @@ -1599,6 +1601,72 @@ class Y(TypedDict):
error=None,
)

@collect_cases
def test_named_tuple(self) -> Iterator[Case]:
yield Case(
stub="from typing import NamedTuple",
runtime="from typing import NamedTuple",
error=None,
)
yield Case(
stub="""
class X1(NamedTuple):
bar: int
foo: str = ...
""",
runtime="""
class X1(NamedTuple):
bar: int
foo: str = 'a'
""",
error=None,
)
yield Case(
stub="""
class X2(NamedTuple):
bar: int
foo: str
""",
runtime="""
class X2(NamedTuple):
bar: int
foo: str = 'a'
""",
# `__new__` will miss a default value for a `foo` parameter,
# but we don't generate special errors for `foo` missing `...` part.
error="X2.__new__",
)

@collect_cases
def test_named_tuple_typing_and_collections(self) -> Iterator[Case]:
yield Case(
stub="from typing import NamedTuple",
runtime="from collections import namedtuple",
error=None,
)
yield Case(
stub="""
class X1(NamedTuple):
bar: int
foo: str = ...
""",
runtime="""
X1 = namedtuple('X1', ['bar', 'foo'], defaults=['a'])
""",
error=None,
)
yield Case(
stub="""
class X2(NamedTuple):
bar: int
foo: str
""",
runtime="""
X2 = namedtuple('X1', ['bar', 'foo'], defaults=['a'])
""",
error="X2.__new__",
)

@collect_cases
def test_type_var(self) -> Iterator[Case]:
yield Case(
Expand Down

0 comments on commit 14efdf2

Please sign in to comment.