def test_series_invert() -> None: s1 = pd.Series([True, False, True]) s2 = ~s1 assert_type(s2, "pd.Series[bool]") s3 = pd.Series([1, 2, 3]) check_series_result(s3[s2]) check_series_result(s3.loc[s2])
def test_serialization_containing_delimiter(uuid_key): model = MyModel() model.key = uuid_key model.default_delimiter = MyTuple(country="U::S", city="San Francisco") assert_type(model.default_delimiter, MyTuple) assert_type(model.default_delimiter.country, str) with pytest.raises(ValueError): model.save()
def test_timestamp_plus_timedelta_series() -> None: tscheck = pd.Series( [pd.Timestamp("2022-03-05"), pd.Timestamp("2022-03-06")]) ts = pd.Timestamp("2022-03-05") td = pd.to_timedelta(pd.Series([10, 20]), "minutes") r3 = td + ts assert_type(r3, "TimestampSeries") # ignore type on next, because `tscheck` has Unknown dtype check_series_result(r3, tscheck.dtype) # type: ignore
def test_serialization_untyped(expected_attributes, value, uuid_key): model = MyModel() model.key = uuid_key model.untyped = value model.save() # verify underlying storage item = _connection(MyModel).get_item(uuid_key) assert item["Item"] == {"key": ANY, **expected_attributes} # verify deserialization model = MyModel.get(uuid_key) assert model.untyped == value assert_type(MyModel.untyped, UnicodeDelimitedTupleAttribute[Tuple[Any, ...]])
async def test_gather(awaitable1: Awaitable[int], awaitable2: Awaitable[str]) -> None: a = await asyncio.gather(awaitable1) assert_type(a, Tuple[int]) b = await asyncio.gather(awaitable1, awaitable2, return_exceptions=True) assert_type(b, Tuple[Union[int, BaseException], Union[str, BaseException]]) c = await asyncio.gather(awaitable1, awaitable2, awaitable1, awaitable1, awaitable1, awaitable1) assert_type(c, List[Any]) awaitables_list: List[Awaitable[int]] = [awaitable1] d = await asyncio.gather(*awaitables_list) assert_type(d, List[Any]) e = await asyncio.gather() assert_type(e, List[Any])
def test_series_min_max_sub_axis() -> None: df = pd.DataFrame({"x": [1, 2, 3, 4, 5], "y": [5, 4, 3, 2, 1]}) s1 = df.min(axis=1) s2 = df.max(axis=1) sa = s1 + s2 ss = s1 - s2 sm = s1 * s2 sd = s1 / s2 assert_type(sa, "pd.Series") assert_type(ss, "pd.Series") assert_type(sm, "pd.Series") assert_type(sd, "pd.Series")
def test_timestamp_timedelta_series_arithmetic() -> None: ts = pd.Timestamp("2022-03-05") s1 = pd.Series(["2022-03-05", "2022-03-06"]) ts1 = pd.to_datetime(pd.Series(["2022-03-05", "2022-03-06"])) assert isinstance(ts1.iloc[0], pd.Timestamp) td1 = pd.to_timedelta([2, 3], "seconds") ts2 = pd.to_datetime(pd.Series(["2022-03-08", "2022-03-10"])) r1 = ts1 - ts2 assert_type(r1, "TimedeltaSeries") check_series_result(r1, td1.dtype) # type: ignore r2 = r1 / td1 check_series_result(r2, float) r3 = r1 - td1 check_series_result(r3, td1.dtype) # type: ignore r4 = pd.Timedelta(5, "days") / r1 check_series_result(r4, float) sb = pd.Series([1, 2]) == pd.Series([1, 3]) check_series_result(sb, bool) r5 = sb * r1 check_series_result(r5, r1.dtype) r6 = r1 * 4 check_series_result(r6, r1.dtype)
def test_iscoroutinefunction( x: Callable[[str, int], Coroutine[str, int, bytes]], y: Callable[[str, int], Awaitable[bytes]], z: Callable[[str, int], Union[str, Awaitable[bytes]]], xx: object, ) -> None: if iscoroutinefunction(x): assert_type(x, Callable[[str, int], Coroutine[str, int, bytes]]) if iscoroutinefunction(y): assert_type(y, Callable[[str, int], Coroutine[Any, Any, bytes]]) if iscoroutinefunction(z): assert_type(z, Callable[[str, int], Coroutine[Any, Any, Any]]) if iscoroutinefunction(xx): assert_type(xx, Callable[..., Coroutine[Any, Any, Any]])
def test_timedelta_series_mult() -> None: df = pd.DataFrame({"x": [1, 3, 5], "y": [2, 2, 6]}) std = (df["x"] < df["y"]) * pd.Timedelta(10, "minutes") assert_type(std, "TimedeltaSeries")
def test_config_types() -> None: """ We use `assert_type` to test the types returned by Config via mypy. """ config = Config( environ={"STR": "some_str_value", "STR_CAST": "some_str_value", "BOOL": "true"} ) assert_type(config("STR"), str) assert_type(config("STR_DEFAULT", default=""), str) assert_type(config("STR_CAST", cast=str), str) assert_type(config("STR_NONE", default=None), Optional[str]) assert_type(config("STR_CAST_NONE", cast=str, default=None), Optional[str]) assert_type(config("STR_CAST_STR", cast=str, default=""), str) assert_type(config("BOOL", cast=bool), bool) assert_type(config("BOOL_DEFAULT", cast=bool, default=False), bool) assert_type(config("BOOL_NONE", cast=bool, default=None), Optional[bool]) def cast_to_int(v: Any) -> int: return int(v) # our type annotations allow these `cast` and `default` configurations, but # the code will error at runtime. with pytest.raises(ValueError): config("INT_CAST_DEFAULT_STR", cast=cast_to_int, default="true") with pytest.raises(ValueError): config("INT_DEFAULT_STR", cast=int, default="true")
from typing import List, Union from typing_extensions import assert_type # list.__add__ example from #8292 class Foo: def asd(self) -> int: return 1 class Bar: def asd(self) -> int: return 2 combined = [Foo()] + [Bar()] assert_type(combined, List[Union[Foo, Bar]]) for item in combined: assert_type(item.asd(), int)
from contextlib import ExitStack from typing_extensions import assert_type # See issue #7961 class Thing(ExitStack): pass stack = ExitStack() thing = Thing() assert_type(stack.enter_context(Thing()), Thing) assert_type(thing.enter_context(ExitStack()), ExitStack) with stack as cm: assert_type(cm, ExitStack) with thing as cm2: assert_type(cm2, Thing)
@pytest.fixture(scope="module", autouse=True) def create_table(): MyModel.create_table() class MyModel(Model): Meta = dynamodb_table_meta(__name__) key = UnicodeAttribute(hash_key=True) default_delimiter = UnicodeDelimitedTupleAttribute(MyTuple, null=True) custom_delimiter = UnicodeDelimitedTupleAttribute(MyTuple, delimiter=".", null=True) untyped = UnicodeDelimitedTupleAttribute(tuple, null=True) assert_type(MyModel.default_delimiter, UnicodeDelimitedTupleAttribute[MyTuple]) assert_type(MyModel.untyped, UnicodeDelimitedTupleAttribute[Tuple[Any, ...]]) def test_serialization_containing_delimiter(uuid_key): model = MyModel() model.key = uuid_key model.default_delimiter = MyTuple(country="U::S", city="San Francisco") assert_type(model.default_delimiter, MyTuple) assert_type(model.default_delimiter.country, str) with pytest.raises(ValueError): model.save()
class MyModel(Model): Meta = dynamodb_table_meta(__name__) key = UnicodeAttribute(hash_key=True) default = UnicodeDatetimeAttribute(null=True) no_force_tz = UnicodeDatetimeAttribute(force_tz=False, null=True) force_utc = UnicodeDatetimeAttribute(force_utc=True, null=True) force_utc_no_force_tz = UnicodeDatetimeAttribute( force_utc=True, force_tz=False, null=True, ) custom_format = UnicodeDatetimeAttribute(fmt=CUSTOM_FORMAT, null=True) assert_type(MyModel.default, UnicodeDatetimeAttribute) assert_type(MyModel().default, datetime) @pytest.fixture(scope="module", autouse=True) def create_table(): MyModel.create_table() @pytest.mark.parametrize( ["value", "expected_str", "expected_value"], [ ( datetime.fromisoformat(TEST_ISO_DATE_NO_OFFSET), TEST_ISO_DATE_UTC, datetime.fromisoformat(TEST_ISO_DATE_UTC),
from typing import Tuple from typing_extensions import assert_type # Empty tuples, see #8275 class TupleSub(Tuple[int, ...]): pass assert_type(TupleSub(), TupleSub) assert_type(TupleSub([1, 2, 3]), TupleSub)
from pynamodb.models import Model from typing_extensions import assert_type from pynamodb_attributes import UUIDAttribute from tests.connection import _connection from tests.meta import dynamodb_table_meta class MyModel(Model): Meta = dynamodb_table_meta(__name__) key = UnicodeAttribute(hash_key=True) value = UUIDAttribute(null=True) assert_type(MyModel.value, UUIDAttribute) assert_type(MyModel().value, UUID) @pytest.fixture(scope="module", autouse=True) def create_table(): MyModel.create_table() def test_deserialization_no_dashes(): uuid_attribute = UUIDAttribute(remove_dashes=True) uuid_str_no_dashes = "19c4f2515e364cc0bfeb983dd5d2bacd" assert UUID( "19c4f251-5e36-4cc0-bfeb-983dd5d2bacd") == uuid_attribute.deserialize( uuid_str_no_dashes, )
from typing import Iterator from typing_extensions import assert_type class OldStyleIter: def __getitem__(self, index: int) -> str: return str(index) for x in iter(OldStyleIter()): assert_type(x, str) assert_type(iter(OldStyleIter()), Iterator[str]) assert_type(next(iter(OldStyleIter())), str)
class MyModel(Model): Meta = dynamodb_table_meta(__name__) key = UnicodeAttribute(hash_key=True) value = UnicodeEnumAttribute(MyEnum, null=True) value_with_unknown = UnicodeEnumAttribute( MyEnum, unknown_value=MyEnum.unknown_key, null=True, ) value_with_missing = UnicodeEnumAttribute(MyEnumWithMissing, null=True) assert_type(MyModel.value, UnicodeEnumAttribute[MyEnum]) assert_type(MyModel().value, MyEnum) @pytest.fixture(scope="module", autouse=True) def create_table(): MyModel.create_table() def test_invalid_enum(): class IntEnum(Enum): foo_key = "foo_value" bar_key = 2 with pytest.raises(TypeError, match="values must be all strings"): UnicodeEnumAttribute(IntEnum)
# pyright: reportUnnecessaryTypeIgnoreComment=true from decimal import Decimal from fractions import Fraction from typing import Any, NoReturn from typing_extensions import Literal, assert_type # See #7163 assert_type(pow(1, 0), Literal[1]) assert_type(1**0, Literal[1]) assert_type(pow(1, 0, None), Literal[1]) assert_type(pow(2, 4, 0), NoReturn) assert_type(pow(2, 4), int) assert_type(2**4, int) assert_type(pow(4, 6, None), int) assert_type(pow(5, -7), float) assert_type(5**-7, float) assert_type(pow(2, 4, 5), int) # pow(<smallint>, <smallint>, <smallint>) assert_type(pow(2, 35, 3), int) # pow(<smallint>, <bigint>, <smallint>) assert_type(pow(2, 8.5), float) assert_type(2**8.6, float) assert_type(pow(2, 8.6, None), float) # TODO: Why does this pass pyright but not mypy?? # assert_type((-2) ** 0.5, complex)
from pynamodb.models import Model from typing_extensions import assert_type from pynamodb_attributes.integer_date import IntegerDateAttribute from tests.connection import _connection from tests.meta import dynamodb_table_meta class MyModel(Model): Meta = dynamodb_table_meta(__name__) key = UnicodeAttribute(hash_key=True) value = IntegerDateAttribute(null=True) assert_type(MyModel.value, IntegerDateAttribute) assert_type(MyModel().value, date) @pytest.fixture(scope="module", autouse=True) def create_table(): MyModel.create_table() def test_serialization_non_null(uuid_key): model = MyModel() model.key = uuid_key model.value = date(2015, 12, 31) model.save() # verify underlying storage
from pynamodb_attributes import TimedeltaMsAttribute from pynamodb_attributes import TimedeltaUsAttribute from tests.connection import _connection from tests.meta import dynamodb_table_meta class MyModel(Model): Meta = dynamodb_table_meta(__name__) key = UnicodeAttribute(hash_key=True) value = TimedeltaAttribute(null=True) value_ms = TimedeltaMsAttribute(null=True) value_us = TimedeltaUsAttribute(null=True) assert_type(MyModel().value, timedelta) assert_type(MyModel().value_ms, timedelta) assert_type(MyModel().value_us, timedelta) @pytest.fixture(scope="module", autouse=True) def create_table(): MyModel.create_table() def test_serialization_non_null(uuid_key): model = MyModel() model.key = uuid_key model.value = model.value_ms = model.value_us = timedelta( seconds=456, microseconds=123456,
from pynamodb.models import Model from typing_extensions import assert_type from pynamodb_attributes import IntegerAttribute from tests.connection import _connection from tests.meta import dynamodb_table_meta class MyModel(Model): Meta = dynamodb_table_meta(__name__) key = UnicodeAttribute(hash_key=True) value = IntegerAttribute(null=True) assert_type(MyModel.value, IntegerAttribute) assert_type(MyModel().value, int) @pytest.fixture(scope="module", autouse=True) def create_table(): MyModel.create_table() def test_serialization_non_null(uuid_key): model = MyModel() model.key = uuid_key model.value = 456 model.save() # verify underlying storage
# pyright: reportUnnecessaryTypeIgnoreComment=true import codecs from typing_extensions import assert_type assert_type(codecs.decode("x", "unicode-escape"), str) assert_type(codecs.decode(b"x", "unicode-escape"), str) assert_type(codecs.decode(b"x", "utf-8"), str) codecs.decode("x", "utf-8") # type: ignore assert_type(codecs.decode("ab", "hex"), bytes) assert_type(codecs.decode(b"ab", "hex"), bytes)
class Bar: def __radd__(self, other: Any) -> "Bar": return Bar() class Baz: def __add__(self, other: Any) -> "Baz": return Baz() def __radd__(self, other: Any) -> "Baz": return Baz() assert_type(sum([2, 4]), int) assert_type(sum([3, 5], 4), int) assert_type(sum([True, False]), int) assert_type(sum([True, False], True), int) assert_type(sum([["foo"], ["bar"]], ["baz"]), List[str]) assert_type(sum([Foo(), Foo()], Foo()), Foo) assert_type(sum([Baz(), Baz()]), Union[Baz, Literal[0]]) # mypy and pyright infer the types differently for these, so we can't use assert_type # Just test that no error is emitted for any of these sum( [("foo", ), ("bar", "baz")], () ) # mypy: `tuple[str, ...]`; pyright: `tuple[()] | tuple[str] | tuple[str, str]`
def test_search(str_pat: Pattern[str], bytes_pat: Pattern[bytes]) -> None: assert_type(str_pat.search("x"), Optional[Match[str]]) assert_type(bytes_pat.search(b"x"), Optional[Match[bytes]]) assert_type(bytes_pat.search(bytearray(b"x")), Optional[Match[bytes]])