Skip to content

Commit

Permalink
fixed tests and linters for pydantic 2.x
Browse files Browse the repository at this point in the history
  • Loading branch information
bomzheg committed Aug 29, 2023
1 parent 957f62d commit 340ef48
Show file tree
Hide file tree
Showing 12 changed files with 271 additions and 217 deletions.
388 changes: 221 additions & 167 deletions poetry.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ types-openpyxl = "*"
types-python-jose = "*"
types-passlib = "*"
mypy = "^1.1.1"
aiogram-tests = {git = "https://github.com/bomzheg/aiogram_tests.git", branch = "master"}
aiogram-tests = {git = "https://github.com/bomzheg/aiogram_tests.git", branch = "fix/aiogram3rc"}

[build-system]
requires = ["poetry-core"]
Expand Down
2 changes: 1 addition & 1 deletion shvatka/api/routes/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
async def get_my_games_list(
player: dto.Player = Depends(player_provider), # type: ignore[assignment]
dao: HolderDao = Depends(dao_provider), # type: ignore[assignment]
) -> list[dto.Game]:
):
return await get_authors_games(player, dao.game)


Expand Down
6 changes: 4 additions & 2 deletions shvatka/infrastructure/db/models/base.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from typing import Mapping

from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase

convention = {
convention: Mapping[str, str] = {
"ix": "ix__%(column_0_label)s",
"uq": "uq__%(table_name)s__%(column_0_name)s",
"ck": "ck__%(table_name)s__%(constraint_name)s",
"fk": "%(table_name)s_%(column_0_name)s_fkey",
"pk": "pk__%(table_name)s",
}
meta = MetaData(naming_convention=convention)
meta = MetaData(naming_convention=convention) # type: ignore[arg-type]


class Base(DeclarativeBase):
Expand Down
4 changes: 2 additions & 2 deletions shvatka/tgbot/dialogs/game_publish/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Any

from aiogram import Bot
from aiogram.types import Message
from aiogram.types import Message, ChatMemberAdministrator
from aiogram.utils.text_decorations import html_decoration as hd
from aiogram_dialog import DialogManager, BaseDialogManager
from telegraph.aio import Telegraph
Expand All @@ -30,7 +30,7 @@ async def process_publish_message(message: Message, dialog_: Any, manager: Dialo
if admin.user.id == bot.id:
bot_admin = admin
break
if bot_admin is None or bot_admin.status != "administrator":
if bot_admin is None or not isinstance(bot_admin, ChatMemberAdministrator):
return await message.answer("Я не админ в том канале.")
if not bot_admin.can_post_messages:
return await message.answer("У меня нет прав на отправку сообщений в том канале")
Expand Down
24 changes: 12 additions & 12 deletions shvatka/tgbot/models/hint.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def kwargs(self) -> dict:
class AudioLinkView(BaseHintLinkView):
file_id: str
caption: str
thumb: str | None
thumb: str | None = None

def kwargs(self) -> dict:
return dict(audio=self.file_id, caption=self.caption)
Expand All @@ -89,21 +89,21 @@ def kwargs(self) -> dict:
class AudioContentView(BaseHintContentView):
content: BinaryIO
caption: str
thumb: BinaryIO | None
thumb: BinaryIO | None = None

def kwargs(self) -> dict:
return dict(
audio=_get_input_file(self.content),
caption=self.caption,
thumb=_get_input_file(self.thumb),
thumbnail=_get_input_file(self.thumb),
)


@dataclass
class VideoLinkView(BaseHintLinkView):
file_id: str
caption: str
thumb: str | None
thumb: str | None = None

def kwargs(self) -> dict:
return dict(video=self.file_id, caption=self.caption)
Expand All @@ -113,21 +113,21 @@ def kwargs(self) -> dict:
class VideoContentView(BaseHintContentView):
content: BinaryIO
caption: str
thumb: BinaryIO | None
thumb: BinaryIO | None = None

def kwargs(self) -> dict:
return dict(
video=_get_input_file(self.content),
caption=self.caption,
thumb=_get_input_file(self.thumb),
thumbnail=_get_input_file(self.thumb),
)


@dataclass
class DocumentLinkView(BaseHintLinkView):
file_id: str
caption: str
thumb: str | None
thumb: str | None = None

def kwargs(self) -> dict:
return dict(document=self.file_id, caption=self.caption)
Expand All @@ -137,21 +137,21 @@ def kwargs(self) -> dict:
class DocumentContentView(BaseHintContentView):
content: BinaryIO
caption: str
thumb: BinaryIO | None
thumb: BinaryIO | None = None

def kwargs(self) -> dict:
return dict(
document=_get_input_file(self.content),
caption=self.caption,
thumb=_get_input_file(self.thumb),
thumbnail=_get_input_file(self.thumb),
)


@dataclass
class AnimationLinkView(BaseHintLinkView):
file_id: str
caption: str
thumb: str | None
thumb: str | None = None

def kwargs(self) -> dict:
return dict(animation=self.file_id, caption=self.caption)
Expand All @@ -161,13 +161,13 @@ def kwargs(self) -> dict:
class AnimationContentView(BaseHintContentView):
content: BinaryIO
caption: str
thumb: BinaryIO | None
thumb: BinaryIO | None = None

def kwargs(self) -> dict:
return dict(
animation=_get_input_file(self.content),
caption=self.caption,
thumb=_get_input_file(self.thumb),
thumbnail=_get_input_file(self.thumb),
)


Expand Down
8 changes: 4 additions & 4 deletions shvatka/tgbot/services/inline_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def pack(self) -> str:
:return: valid inline data for Telegram Bot API
"""
result = [self.__prefix__]
for key, value in self.dict().items():
for key, value in self.model_dump().items():
encoded = self._encode_value(key, value)
if self.__separator__ in encoded:
raise ValueError(
Expand All @@ -95,7 +95,7 @@ def unpack(cls: Type[T], value: str) -> T:
:return: instance of InlineData
"""
prefix, *parts = value.split(cls.__separator__)
names = cls.__fields__.keys()
names = cls.model_fields.keys()
if len(parts) != len(names):
raise TypeError(
f"Inline data {cls.__name__!r} takes {len(names)} arguments "
Expand All @@ -105,8 +105,8 @@ def unpack(cls: Type[T], value: str) -> T:
raise ValueError(f"Bad prefix ({prefix!r} != {cls.__prefix__!r})")
payload = {}
for k, v in zip(names, parts): # type: str, Optional[str]
if field := cls.__fields__.get(k):
if v == "" and not field.required:
if field := cls.model_fields.get(k):
if v == "" and not field.is_required():
v = None
payload[k] = v
return cls(**payload)
Expand Down
2 changes: 0 additions & 2 deletions shvatka/tgbot/views/hint_factory/hint_content_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,12 @@ async def resolve_content(self, hint: BaseHint) -> BaseHintContentView:
return AudioContentView(
content=await self._resolve_bytes(hint.file_guid),
caption=hint.caption,
thumb=await self._resolve_bytes(hint.thumb_guid),
)
case VideoHint():
hint = typing.cast(VideoHint, hint)
return VideoContentView(
content=await self._resolve_bytes(hint.file_guid),
caption=hint.caption,
thumb=await self._resolve_bytes(hint.thumb_guid),
)
case DocumentHint():
hint = typing.cast(DocumentHint, hint)
Expand Down
8 changes: 4 additions & 4 deletions shvatka/tgbot/views/hint_factory/hint_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,31 +67,31 @@ async def parse(self, message: Message, author: dto.Player) -> BaseHint:
return PhotoHint(caption=message.html_text, file_guid=guid)
case ContentType.AUDIO:
assert message.audio
thumb = await self.save_thumb(author, message.audio.thumb)
thumb = await self.save_thumb(author, message.audio.thumbnail)
return AudioHint(
caption=message.html_text,
file_guid=guid,
thumb_guid=thumb.guid if thumb else None,
)
case ContentType.VIDEO:
assert message.video
thumb = await self.save_thumb(author, message.video.thumb)
thumb = await self.save_thumb(author, message.video.thumbnail)
return VideoHint(
caption=message.html_text,
file_guid=guid,
thumb_guid=thumb.guid if thumb else None,
)
case ContentType.DOCUMENT:
assert message.document
thumb = await self.save_thumb(author, message.document.thumb)
thumb = await self.save_thumb(author, message.document.thumbnail)
return DocumentHint(
caption=message.html_text,
file_guid=guid,
thumb_guid=thumb.guid if thumb else None,
)
case ContentType.ANIMATION:
assert message.animation
thumb = await self.save_thumb(author, message.animation.thumb)
thumb = await self.save_thumb(author, message.animation.thumbnail)
return AnimationHint(
caption=message.html_text,
file_guid=guid,
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/bot_full/test_full_team_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async def test_create_team(harry: dto.Player, dp: Dispatcher, bot: MockedBot, da
update_id=1,
message=Message(
message_id=2,
from_user=harry_tg, # type: ignore[call-arg]
from_user=harry_tg,
chat=chat,
text="/" + CREATE_TEAM_COMMAND.command,
date=datetime.now(tz=tz_utc),
Expand All @@ -58,7 +58,7 @@ async def test_create_team(harry: dto.Player, dp: Dispatcher, bot: MockedBot, da
hermi = create_dto_hermione()
hermi_message = Message(
message_id=3,
from_user=create_tg_from_dto(hermi), # type: ignore[call-arg]
from_user=create_tg_from_dto(hermi),
chat=chat,
text="hi everyone",
date=datetime.now(tz=tz_utc),
Expand All @@ -79,7 +79,7 @@ async def test_create_team(harry: dto.Player, dp: Dispatcher, bot: MockedBot, da
update_id=3,
message=Message(
message_id=4,
from_user=harry_tg, # type: ignore[call-arg]
from_user=harry_tg,
chat=chat,
text=f"/{ADD_IN_TEAM_COMMAND.command} brain",
reply_to_message=hermi_message,
Expand Down
36 changes: 18 additions & 18 deletions tests/integration/bot_full/test_hint_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ async def test_send_text(hint_sender: HintSender):
await hint_sender.send_hint(hint, CHAT_ID)

request = bot.session.requests.pop()
assert request.method == "sendMessage"
assert request.data["text"] == hint.text
assert request.__api_method__ == "sendMessage"
assert request.text == hint.text
assert 0 == len(bot.session.requests)


Expand All @@ -86,9 +86,9 @@ async def test_send_location(hint_sender: HintSender):
await hint_sender.send_hint(hint, CHAT_ID)

request = bot.session.requests.pop()
assert request.method == "sendLocation"
assert request.data["longitude"] == hint.longitude
assert request.data["latitude"] == hint.latitude
assert request.__api_method__ == "sendLocation"
assert request.longitude == hint.longitude
assert request.latitude == hint.latitude
assert 0 == len(bot.session.requests)


Expand All @@ -101,13 +101,13 @@ async def test_send_venue(hint_sender: HintSender):
await hint_sender.send_hint(hint, CHAT_ID)

request = bot.session.requests.pop()
assert request.method == "sendVenue"
assert request.data["longitude"] == hint.longitude
assert request.data["latitude"] == hint.latitude
assert request.data["title"] == hint.title
assert request.data["address"] == hint.address
assert request.data["foursquare_id"] == hint.foursquare_id
assert request.data["foursquare_type"] == hint.foursquare_type
assert request.__api_method__ == "sendVenue"
assert request.longitude == hint.longitude
assert request.latitude == hint.latitude
assert request.title == hint.title
assert request.address == hint.address
assert request.foursquare_id == hint.foursquare_id
assert request.foursquare_type == hint.foursquare_type
assert 0 == len(bot.session.requests)


Expand All @@ -129,8 +129,8 @@ async def test_send_photo_by_id(
await hint_sender.send_hint(hint, CHAT_ID)

request = bot.session.requests.pop()
assert request.method == method_name
assert request.data[content_type] == FILE_ID
assert request.__api_method__ == method_name
assert getattr(request, content_type) == FILE_ID
assert 0 == len(bot.session.requests)


Expand Down Expand Up @@ -158,10 +158,10 @@ async def test_send_photo_by_content(

assert 2 == len(bot.session.requests)
request = bot.session.requests.popleft()
assert request.method == method_name
assert request.data[content_type] == FILE_ID
assert request.__api_method__ == method_name
assert getattr(request, content_type) == FILE_ID

request = bot.session.requests.popleft()
assert request.method == method_name
assert request.files[content_type] is not None
assert request.__api_method__ == method_name
assert getattr(request, content_type) is not None
assert 0 == len(bot.session.requests)
2 changes: 1 addition & 1 deletion tests/integration/bot_full/test_level_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ async def test_write_level(
)
message_manager.assert_answered(callback_id)
request = bot.session.get_request()
assert "Уровень успешно сохранён" == request.data["text"]
assert "Уровень успешно сохранён" == request.text
assert 1 == await dao.level.count()
level, *_ = await dao.level.get_all_my(author)
assert author.id == level.author.id
Expand Down

0 comments on commit 340ef48

Please sign in to comment.