Files
pydantic/tests/test_typing.py
T
Davis Kirkendall 3d287594e0 Allow collections.abc.Callable to be used as type in python 3.9 (#2519)
* Allow collections.abc.Callable to be used as type in python 3.9

* Add is_none_type as function to check none types by identity

* Modify `typing.is_none_type` to work in python 3.6 and 3.7

* Add tests for none types in typing.py

* Apply review comments on #2519
* Add different implementations depending on python version
* Add tests for is_none_type

* Add change entry

* Fix field info repr

* Remove unneeded try/except for python < 3.8

* Add comment explaining alternative is_none_type implementation

* fix: typo

Co-authored-by: PrettyWood <em.jolibois@gmail.com>
2021-09-04 00:25:28 +02:00

69 lines
1.9 KiB
Python

from collections import namedtuple
from typing import Callable as TypingCallable, NamedTuple
import pytest
from pydantic.typing import Literal, is_namedtuple, is_none_type, is_typeddict
try:
from typing import TypedDict as typing_TypedDict
except ImportError:
typing_TypedDict = None
try:
from typing_extensions import TypedDict as typing_extensions_TypedDict
except ImportError:
typing_extensions_TypedDict = None
try:
from mypy_extensions import TypedDict as mypy_extensions_TypedDict
except ImportError:
mypy_extensions_TypedDict = None
ALL_TYPEDDICT_KINDS = (typing_TypedDict, typing_extensions_TypedDict, mypy_extensions_TypedDict)
def test_is_namedtuple():
class Employee(NamedTuple):
name: str
id: int = 3
assert is_namedtuple(namedtuple('Point', 'x y')) is True
assert is_namedtuple(Employee) is True
assert is_namedtuple(NamedTuple('Employee', [('name', str), ('id', int)])) is True
class Other(tuple):
name: str
id: int
assert is_namedtuple(Other) is False
@pytest.mark.parametrize('TypedDict', (t for t in ALL_TYPEDDICT_KINDS if t is not None))
def test_is_typeddict_typing(TypedDict):
class Employee(TypedDict):
name: str
id: int
assert is_typeddict(Employee) is True
assert is_typeddict(TypedDict('Employee', {'name': str, 'id': int})) is True
class Other(dict):
name: str
id: int
assert is_typeddict(Other) is False
def test_is_none_type():
assert is_none_type(Literal[None]) is True
assert is_none_type(None) is True
assert is_none_type(type(None)) is True
assert is_none_type(6) is False
assert is_none_type({}) is False
# WARNING: It's important to test `typing.Callable` not
# `collections.abc.Callable` (even with python >= 3.9) as they behave
# differently
assert is_none_type(TypingCallable) is False