#1370 added possibility to check X | None on Python >= 3.10

This commit is contained in:
JRoot Junior 2023-11-20 22:49:55 +02:00
parent e17e3bc71c
commit ce4e1a706d
No known key found for this signature in database
GPG key ID: 738964250D5FF6E2
2 changed files with 19 additions and 1 deletions

View file

@ -1,5 +1,7 @@
from __future__ import annotations
import sys
import types
import typing
from decimal import Decimal
from enum import Enum
@ -29,6 +31,11 @@ T = TypeVar("T", bound="CallbackData")
MAX_CALLBACK_LENGTH: int = 64
_UNION_TYPES = {typing.Union}
if sys.version_info >= (3, 10): # pragma: no cover
_UNION_TYPES.add(types.UnionType)
class CallbackDataException(Exception):
pass
@ -195,6 +202,6 @@ def _check_field_is_nullable(field: FieldInfo) -> bool:
if not field.is_required():
return True
return typing.get_origin(field.annotation) is typing.Union and type(None) in typing.get_args(
return typing.get_origin(field.annotation) in _UNION_TYPES and type(None) in typing.get_args(
field.annotation
)

View file

@ -1,3 +1,4 @@
import sys
from decimal import Decimal
from enum import Enum, auto
from fractions import Fraction
@ -163,6 +164,16 @@ class TestCallbackData:
assert TgData.unpack("tg:123:") == TgData(chat_id=123, thread_id=None)
@pytest.mark.skipif(sys.version_info < (3, 10), reason="UnionType is added in Python 3.10")
def test_unpack_optional_wo_default_union_type(self):
"""Test CallbackData without default optional."""
class TgData(CallbackData, prefix="tg"):
chat_id: int
thread_id: int | None
assert TgData.unpack("tg:123:") == TgData(chat_id=123, thread_id=None)
def test_build_filter(self):
filter_object = MyCallback.filter(F.foo == "test")
assert isinstance(filter_object.rule, MagicFilter)