Enforce the offline_bot Fixture in Test*WithoutRequest (#4465)

This commit is contained in:
Bibo-Joshi 2024-09-13 19:10:09 +02:00 committed by GitHub
parent 1223e851c3
commit ec909e62cf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
76 changed files with 930 additions and 829 deletions

View file

@ -84,7 +84,7 @@ class TestAnimationWithoutRequest(AnimationTestBase):
assert animation.file_name.startswith("game.gif") == self.file_name.startswith("game.gif") assert animation.file_name.startswith("game.gif") == self.file_name.startswith("game.gif")
assert isinstance(animation.thumbnail, PhotoSize) assert isinstance(animation.thumbnail, PhotoSize)
def test_de_json(self, bot, animation): def test_de_json(self, offline_bot, animation):
json_dict = { json_dict = {
"file_id": self.animation_file_id, "file_id": self.animation_file_id,
"file_unique_id": self.animation_file_unique_id, "file_unique_id": self.animation_file_unique_id,
@ -96,7 +96,7 @@ class TestAnimationWithoutRequest(AnimationTestBase):
"mime_type": self.mime_type, "mime_type": self.mime_type,
"file_size": self.file_size, "file_size": self.file_size,
} }
animation = Animation.de_json(json_dict, bot) animation = Animation.de_json(json_dict, offline_bot)
assert animation.api_kwargs == {} assert animation.api_kwargs == {}
assert animation.file_id == self.animation_file_id assert animation.file_id == self.animation_file_id
assert animation.file_unique_id == self.animation_file_unique_id assert animation.file_unique_id == self.animation_file_unique_id
@ -140,18 +140,22 @@ class TestAnimationWithoutRequest(AnimationTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_send_animation_custom_filename(self, bot, chat_id, animation_file, monkeypatch): async def test_send_animation_custom_filename(
self, offline_bot, chat_id, animation_file, monkeypatch
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" return next(iter(request_data.multipart_data.values()))[0] == "custom_filename"
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_animation(chat_id, animation_file, filename="custom_filename") assert await offline_bot.send_animation(
chat_id, animation_file, filename="custom_filename"
)
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_animation_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_animation_local_files(self, monkeypatch, offline_bot, chat_id, local_mode):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -167,18 +171,18 @@ class TestAnimationWithoutRequest(AnimationTestBase):
data.get("thumbnail"), InputFile data.get("thumbnail"), InputFile
) )
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_animation(chat_id, file, thumbnail=file) await offline_bot.send_animation(chat_id, file, thumbnail=file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_send_with_animation(self, monkeypatch, bot, chat_id, animation): async def test_send_with_animation(self, monkeypatch, offline_bot, chat_id, animation):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["animation"] == animation.file_id return request_data.json_parameters["animation"] == animation.file_id
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_animation(animation=animation, chat_id=chat_id) assert await offline_bot.send_animation(animation=animation, chat_id=chat_id)
async def test_get_file_instance_method(self, monkeypatch, animation): async def test_get_file_instance_method(self, monkeypatch, animation):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -91,7 +91,7 @@ class TestAudioWithoutRequest(AudioTestBase):
assert audio.thumbnail.width == self.thumb_width assert audio.thumbnail.width == self.thumb_width
assert audio.thumbnail.height == self.thumb_height assert audio.thumbnail.height == self.thumb_height
def test_de_json(self, bot, audio): def test_de_json(self, offline_bot, audio):
json_dict = { json_dict = {
"file_id": self.audio_file_id, "file_id": self.audio_file_id,
"file_unique_id": self.audio_file_unique_id, "file_unique_id": self.audio_file_unique_id,
@ -103,7 +103,7 @@ class TestAudioWithoutRequest(AudioTestBase):
"file_size": self.file_size, "file_size": self.file_size,
"thumbnail": audio.thumbnail.to_dict(), "thumbnail": audio.thumbnail.to_dict(),
} }
json_audio = Audio.de_json(json_dict, bot) json_audio = Audio.de_json(json_dict, offline_bot)
assert json_audio.api_kwargs == {} assert json_audio.api_kwargs == {}
assert json_audio.file_id == self.audio_file_id assert json_audio.file_id == self.audio_file_id
@ -147,25 +147,25 @@ class TestAudioWithoutRequest(AudioTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_send_with_audio(self, monkeypatch, bot, chat_id, audio): async def test_send_with_audio(self, monkeypatch, offline_bot, chat_id, audio):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["audio"] == audio.file_id return request_data.json_parameters["audio"] == audio.file_id
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_audio(audio=audio, chat_id=chat_id) assert await offline_bot.send_audio(audio=audio, chat_id=chat_id)
async def test_send_audio_custom_filename(self, bot, chat_id, audio_file, monkeypatch): async def test_send_audio_custom_filename(self, offline_bot, chat_id, audio_file, monkeypatch):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" return next(iter(request_data.multipart_data.values()))[0] == "custom_filename"
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_audio(chat_id, audio_file, filename="custom_filename") assert await offline_bot.send_audio(chat_id, audio_file, filename="custom_filename")
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_audio_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_audio_local_files(self, monkeypatch, offline_bot, chat_id, local_mode):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -179,11 +179,11 @@ class TestAudioWithoutRequest(AudioTestBase):
data.get("thumbnail"), InputFile data.get("thumbnail"), InputFile
) )
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_audio(chat_id, file, thumbnail=file) await offline_bot.send_audio(chat_id, file, thumbnail=file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_get_file_instance_method(self, monkeypatch, audio): async def test_get_file_instance_method(self, monkeypatch, audio):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -66,14 +66,14 @@ class TestChatPhotoWithoutRequest(ChatPhotoTestBase):
assert getattr(chat_photo, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(chat_photo, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(chat_photo)) == len(set(mro_slots(chat_photo))), "duplicate slot" assert len(mro_slots(chat_photo)) == len(set(mro_slots(chat_photo))), "duplicate slot"
def test_de_json(self, bot, chat_photo): def test_de_json(self, offline_bot, chat_photo):
json_dict = { json_dict = {
"small_file_id": self.chatphoto_small_file_id, "small_file_id": self.chatphoto_small_file_id,
"big_file_id": self.chatphoto_big_file_id, "big_file_id": self.chatphoto_big_file_id,
"small_file_unique_id": self.chatphoto_small_file_unique_id, "small_file_unique_id": self.chatphoto_small_file_unique_id,
"big_file_unique_id": self.chatphoto_big_file_unique_id, "big_file_unique_id": self.chatphoto_big_file_unique_id,
} }
chat_photo = ChatPhoto.de_json(json_dict, bot) chat_photo = ChatPhoto.de_json(json_dict, offline_bot)
assert chat_photo.api_kwargs == {} assert chat_photo.api_kwargs == {}
assert chat_photo.small_file_id == self.chatphoto_small_file_id assert chat_photo.small_file_id == self.chatphoto_small_file_id
assert chat_photo.big_file_id == self.chatphoto_big_file_id assert chat_photo.big_file_id == self.chatphoto_big_file_id
@ -121,12 +121,14 @@ class TestChatPhotoWithoutRequest(ChatPhotoTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_send_with_chat_photo(self, monkeypatch, bot, super_group_id, chat_photo): async def test_send_with_chat_photo(
self, monkeypatch, offline_bot, super_group_id, chat_photo
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters["photo"] == chat_photo.to_dict() return request_data.parameters["photo"] == chat_photo.to_dict()
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
message = await bot.set_chat_photo(photo=chat_photo, chat_id=super_group_id) message = await offline_bot.set_chat_photo(photo=chat_photo, chat_id=super_group_id)
assert message assert message
async def test_get_small_file_instance_method(self, monkeypatch, chat_photo): async def test_get_small_file_instance_method(self, monkeypatch, chat_photo):

View file

@ -52,22 +52,22 @@ class TestContactWithoutRequest(ContactTestBase):
assert getattr(contact, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(contact, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(contact)) == len(set(mro_slots(contact))), "duplicate slot" assert len(mro_slots(contact)) == len(set(mro_slots(contact))), "duplicate slot"
def test_de_json_required(self, bot): def test_de_json_required(self, offline_bot):
json_dict = {"phone_number": self.phone_number, "first_name": self.first_name} json_dict = {"phone_number": self.phone_number, "first_name": self.first_name}
contact = Contact.de_json(json_dict, bot) contact = Contact.de_json(json_dict, offline_bot)
assert contact.api_kwargs == {} assert contact.api_kwargs == {}
assert contact.phone_number == self.phone_number assert contact.phone_number == self.phone_number
assert contact.first_name == self.first_name assert contact.first_name == self.first_name
def test_de_json_all(self, bot): def test_de_json_all(self, offline_bot):
json_dict = { json_dict = {
"phone_number": self.phone_number, "phone_number": self.phone_number,
"first_name": self.first_name, "first_name": self.first_name,
"last_name": self.last_name, "last_name": self.last_name,
"user_id": self.user_id, "user_id": self.user_id,
} }
contact = Contact.de_json(json_dict, bot) contact = Contact.de_json(json_dict, offline_bot)
assert contact.api_kwargs == {} assert contact.api_kwargs == {}
assert contact.phone_number == self.phone_number assert contact.phone_number == self.phone_number
@ -104,20 +104,20 @@ class TestContactWithoutRequest(ContactTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_send_contact_without_required(self, bot, chat_id): async def test_send_contact_without_required(self, offline_bot, chat_id):
with pytest.raises(ValueError, match="Either contact or phone_number and first_name"): with pytest.raises(ValueError, match="Either contact or phone_number and first_name"):
await bot.send_contact(chat_id=chat_id) await offline_bot.send_contact(chat_id=chat_id)
async def test_send_mutually_exclusive(self, bot, chat_id, contact): async def test_send_mutually_exclusive(self, offline_bot, chat_id, contact):
with pytest.raises(ValueError, match="Not both"): with pytest.raises(ValueError, match="Not both"):
await bot.send_contact( await offline_bot.send_contact(
chat_id=chat_id, chat_id=chat_id,
contact=contact, contact=contact,
phone_number=contact.phone_number, phone_number=contact.phone_number,
first_name=contact.first_name, first_name=contact.first_name,
) )
async def test_send_with_contact(self, monkeypatch, bot, chat_id, contact): async def test_send_with_contact(self, monkeypatch, offline_bot, chat_id, contact):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters data = request_data.json_parameters
phone = data["phone_number"] == contact.phone_number phone = data["phone_number"] == contact.phone_number
@ -125,8 +125,8 @@ class TestContactWithoutRequest(ContactTestBase):
last = data["last_name"] == contact.last_name last = data["last_name"] == contact.last_name
return phone and first and last return phone and first and last
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_contact(contact=contact, chat_id=chat_id) assert await offline_bot.send_contact(contact=contact, chat_id=chat_id)
@pytest.mark.parametrize( @pytest.mark.parametrize(
("default_bot", "custom"), ("default_bot", "custom"),

View file

@ -83,7 +83,7 @@ class TestDocumentWithoutRequest(DocumentTestBase):
assert document.thumbnail.width == self.thumb_width assert document.thumbnail.width == self.thumb_width
assert document.thumbnail.height == self.thumb_height assert document.thumbnail.height == self.thumb_height
def test_de_json(self, bot, document): def test_de_json(self, offline_bot, document):
json_dict = { json_dict = {
"file_id": self.document_file_id, "file_id": self.document_file_id,
"file_unique_id": self.document_file_unique_id, "file_unique_id": self.document_file_unique_id,
@ -92,7 +92,7 @@ class TestDocumentWithoutRequest(DocumentTestBase):
"mime_type": self.mime_type, "mime_type": self.mime_type,
"file_size": self.file_size, "file_size": self.file_size,
} }
test_document = Document.de_json(json_dict, bot) test_document = Document.de_json(json_dict, offline_bot)
assert test_document.api_kwargs == {} assert test_document.api_kwargs == {}
assert test_document.file_id == self.document_file_id assert test_document.file_id == self.document_file_id
@ -128,13 +128,13 @@ class TestDocumentWithoutRequest(DocumentTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_error_send_without_required_args(self, bot, chat_id): async def test_error_send_without_required_args(self, offline_bot, chat_id):
with pytest.raises(TypeError): with pytest.raises(TypeError):
await bot.send_document(chat_id=chat_id) await offline_bot.send_document(chat_id=chat_id)
@pytest.mark.parametrize("disable_content_type_detection", [True, False, None]) @pytest.mark.parametrize("disable_content_type_detection", [True, False, None])
async def test_send_with_document( async def test_send_with_document(
self, monkeypatch, bot, chat_id, document, disable_content_type_detection self, monkeypatch, offline_bot, chat_id, document, disable_content_type_detection
): ):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters data = request_data.parameters
@ -143,9 +143,9 @@ class TestDocumentWithoutRequest(DocumentTestBase):
) )
return data["document"] == document.file_id and type_detection return data["document"] == document.file_id and type_detection
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
message = await bot.send_document( message = await offline_bot.send_document(
document=document, document=document,
chat_id=chat_id, chat_id=chat_id,
disable_content_type_detection=disable_content_type_detection, disable_content_type_detection=disable_content_type_detection,
@ -181,10 +181,10 @@ class TestDocumentWithoutRequest(DocumentTestBase):
) )
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_document_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_document_local_files(self, monkeypatch, offline_bot, chat_id, local_mode):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -200,11 +200,11 @@ class TestDocumentWithoutRequest(DocumentTestBase):
data.get("thumbnail"), InputFile data.get("thumbnail"), InputFile
) )
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_document(chat_id, file, thumbnail=file) await offline_bot.send_document(chat_id, file, thumbnail=file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_get_file_instance_method(self, monkeypatch, document): async def test_get_file_instance_method(self, monkeypatch, document):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -107,14 +107,14 @@ class TestFileWithoutRequest(FileTestBase):
assert getattr(file, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(file, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(file)) == len(set(mro_slots(file))), "duplicate slot" assert len(mro_slots(file)) == len(set(mro_slots(file))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"file_id": self.file_id, "file_id": self.file_id,
"file_unique_id": self.file_unique_id, "file_unique_id": self.file_unique_id,
"file_path": self.file_path, "file_path": self.file_path,
"file_size": self.file_size, "file_size": self.file_size,
} }
new_file = File.de_json(json_dict, bot) new_file = File.de_json(json_dict, offline_bot)
assert new_file.api_kwargs == {} assert new_file.api_kwargs == {}
assert new_file.file_id == self.file_id assert new_file.file_id == self.file_id
@ -131,11 +131,11 @@ class TestFileWithoutRequest(FileTestBase):
assert file_dict["file_path"] == file.file_path assert file_dict["file_path"] == file.file_path
assert file_dict["file_size"] == file.file_size assert file_dict["file_size"] == file.file_size
def test_equality(self, bot): def test_equality(self, offline_bot):
a = File(self.file_id, self.file_unique_id, bot) a = File(self.file_id, self.file_unique_id, offline_bot)
b = File("", self.file_unique_id, bot) b = File("", self.file_unique_id, offline_bot)
c = File(self.file_id, self.file_unique_id, None) c = File(self.file_id, self.file_unique_id, None)
d = File("", "", bot) d = File("", "", offline_bot)
e = Voice(self.file_id, self.file_unique_id, 0) e = Voice(self.file_id, self.file_unique_id, 0)
assert a == b assert a == b
@ -223,7 +223,7 @@ class TestFileWithoutRequest(FileTestBase):
assert buf2[len(buf) :] == buf assert buf2[len(buf) :] == buf
assert buf2[: len(buf)] == buf assert buf2[: len(buf)] == buf
async def test_download_encrypted(self, monkeypatch, bot, encrypted_file): async def test_download_encrypted(self, monkeypatch, offline_bot, encrypted_file):
async def test(*args, **kwargs): async def test(*args, **kwargs):
return data_file("image_encrypted.jpg").read_bytes() return data_file("image_encrypted.jpg").read_bytes()

View file

@ -655,7 +655,7 @@ def media_group_no_caption_only_parse_mode(photo, thumb): # noqa: F811
class TestSendMediaGroupWithoutRequest: class TestSendMediaGroupWithoutRequest:
async def test_send_media_group_throws_error_with_group_caption_and_individual_captions( async def test_send_media_group_throws_error_with_group_caption_and_individual_captions(
self, self,
bot, offline_bot,
chat_id, chat_id,
media_group, media_group,
media_group_no_caption_only_caption_entities, media_group_no_caption_only_caption_entities,
@ -670,11 +670,11 @@ class TestSendMediaGroupWithoutRequest:
ValueError, ValueError,
match="You can only supply either group caption or media with captions.", match="You can only supply either group caption or media with captions.",
): ):
await bot.send_media_group(chat_id, group, caption="foo") await offline_bot.send_media_group(chat_id, group, caption="foo")
async def test_send_media_group_custom_filename( async def test_send_media_group_custom_filename(
self, self,
bot, offline_bot,
chat_id, chat_id,
photo_file, # noqa: F811 photo_file, # noqa: F811
animation_file, # noqa: F811 animation_file, # noqa: F811
@ -690,7 +690,7 @@ class TestSendMediaGroupWithoutRequest:
if result is True: if result is True:
raise Exception("Test was successful") raise Exception("Test was successful")
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
media = [ media = [
InputMediaAnimation(animation_file, filename="custom_filename"), InputMediaAnimation(animation_file, filename="custom_filename"),
@ -700,10 +700,10 @@ class TestSendMediaGroupWithoutRequest:
] ]
with pytest.raises(Exception, match="Test was successful"): with pytest.raises(Exception, match="Test was successful"):
await bot.send_media_group(chat_id, media) await offline_bot.send_media_group(chat_id, media)
async def test_send_media_group_with_thumbs( async def test_send_media_group_with_thumbs(
self, bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811 self, offline_bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811
): ):
async def make_assertion(method, url, request_data: RequestData, *args, **kwargs): async def make_assertion(method, url, request_data: RequestData, *args, **kwargs):
nonlocal input_video nonlocal input_video
@ -715,13 +715,13 @@ class TestSendMediaGroupWithoutRequest:
result = video_check and thumb_check result = video_check and thumb_check
raise Exception(f"Test was {'successful' if result else 'failing'}") raise Exception(f"Test was {'successful' if result else 'failing'}")
monkeypatch.setattr(bot.request, "_request_wrapper", make_assertion) monkeypatch.setattr(offline_bot.request, "_request_wrapper", make_assertion)
input_video = InputMediaVideo(video_file, thumbnail=photo_file) input_video = InputMediaVideo(video_file, thumbnail=photo_file)
with pytest.raises(Exception, match="Test was successful"): with pytest.raises(Exception, match="Test was successful"):
await bot.send_media_group(chat_id, [input_video, input_video]) await offline_bot.send_media_group(chat_id, [input_video, input_video])
async def test_edit_message_media_with_thumb( async def test_edit_message_media_with_thumb(
self, bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811 self, offline_bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811
): ):
async def make_assertion( async def make_assertion(
method: str, url: str, request_data: Optional[RequestData] = None, *args, **kwargs method: str, url: str, request_data: Optional[RequestData] = None, *args, **kwargs
@ -734,10 +734,12 @@ class TestSendMediaGroupWithoutRequest:
result = video_check and thumb_check result = video_check and thumb_check
raise Exception(f"Test was {'successful' if result else 'failing'}") raise Exception(f"Test was {'successful' if result else 'failing'}")
monkeypatch.setattr(bot.request, "_request_wrapper", make_assertion) monkeypatch.setattr(offline_bot.request, "_request_wrapper", make_assertion)
input_video = InputMediaVideo(video_file, thumbnail=photo_file) input_video = InputMediaVideo(video_file, thumbnail=photo_file)
with pytest.raises(Exception, match="Test was successful"): with pytest.raises(Exception, match="Test was successful"):
await bot.edit_message_media(chat_id=chat_id, message_id=123, media=input_video) await offline_bot.edit_message_media(
chat_id=chat_id, message_id=123, media=input_video
)
@pytest.mark.parametrize( @pytest.mark.parametrize(
("default_bot", "custom"), ("default_bot", "custom"),

View file

@ -55,7 +55,7 @@ class TestLocationWithoutRequest(LocationTestBase):
assert getattr(location, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(location, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(location)) == len(set(mro_slots(location))), "duplicate slot" assert len(mro_slots(location)) == len(set(mro_slots(location))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"latitude": self.latitude, "latitude": self.latitude,
"longitude": self.longitude, "longitude": self.longitude,
@ -64,7 +64,7 @@ class TestLocationWithoutRequest(LocationTestBase):
"heading": self.heading, "heading": self.heading,
"proximity_alert_radius": self.proximity_alert_radius, "proximity_alert_radius": self.proximity_alert_radius,
} }
location = Location.de_json(json_dict, bot) location = Location.de_json(json_dict, offline_bot)
assert location.api_kwargs == {} assert location.api_kwargs == {}
assert location.latitude == self.latitude assert location.latitude == self.latitude
@ -96,26 +96,28 @@ class TestLocationWithoutRequest(LocationTestBase):
assert a != d assert a != d
assert hash(a) != hash(d) assert hash(a) != hash(d)
async def test_send_location_without_required(self, bot, chat_id): async def test_send_location_without_required(self, offline_bot, chat_id):
with pytest.raises(ValueError, match="Either location or latitude and longitude"): with pytest.raises(ValueError, match="Either location or latitude and longitude"):
await bot.send_location(chat_id=chat_id) await offline_bot.send_location(chat_id=chat_id)
async def test_edit_location_without_required(self, bot): async def test_edit_location_without_required(self, offline_bot):
with pytest.raises(ValueError, match="Either location or latitude and longitude"): with pytest.raises(ValueError, match="Either location or latitude and longitude"):
await bot.edit_message_live_location(chat_id=2, message_id=3) await offline_bot.edit_message_live_location(chat_id=2, message_id=3)
async def test_send_location_with_all_args(self, bot, location): async def test_send_location_with_all_args(self, offline_bot, location):
with pytest.raises(ValueError, match="Not both"): with pytest.raises(ValueError, match="Not both"):
await bot.send_location(chat_id=1, latitude=2.5, longitude=4.6, location=location) await offline_bot.send_location(
chat_id=1, latitude=2.5, longitude=4.6, location=location
)
async def test_edit_location_with_all_args(self, bot, location): async def test_edit_location_with_all_args(self, offline_bot, location):
with pytest.raises(ValueError, match="Not both"): with pytest.raises(ValueError, match="Not both"):
await bot.edit_message_live_location( await offline_bot.edit_message_live_location(
chat_id=1, message_id=7, latitude=2.5, longitude=4.6, location=location chat_id=1, message_id=7, latitude=2.5, longitude=4.6, location=location
) )
# TODO: Needs improvement with in inline sent live location. # TODO: Needs improvement with in inline sent live location.
async def test_edit_live_inline_message(self, monkeypatch, bot, location): async def test_edit_live_inline_message(self, monkeypatch, offline_bot, location):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters data = request_data.json_parameters
lat = data["latitude"] == str(location.latitude) lat = data["latitude"] == str(location.latitude)
@ -127,8 +129,8 @@ class TestLocationWithoutRequest(LocationTestBase):
live = data["live_period"] == "900" live = data["live_period"] == "900"
return lat and lon and id_ and ha and heading and prox_alert and live return lat and lon and id_ and ha and heading and prox_alert and live
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.edit_message_live_location( assert await offline_bot.edit_message_live_location(
inline_message_id=1234, inline_message_id=1234,
location=location, location=location,
horizontal_accuracy=50, horizontal_accuracy=50,
@ -138,30 +140,30 @@ class TestLocationWithoutRequest(LocationTestBase):
) )
# TODO: Needs improvement with in inline sent live location. # TODO: Needs improvement with in inline sent live location.
async def test_stop_live_inline_message(self, monkeypatch, bot): async def test_stop_live_inline_message(self, monkeypatch, offline_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["inline_message_id"] == "1234" return request_data.json_parameters["inline_message_id"] == "1234"
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.stop_message_live_location(inline_message_id=1234) assert await offline_bot.stop_message_live_location(inline_message_id=1234)
async def test_send_with_location(self, monkeypatch, bot, chat_id, location): async def test_send_with_location(self, monkeypatch, offline_bot, chat_id, location):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
lat = request_data.json_parameters["latitude"] == str(location.latitude) lat = request_data.json_parameters["latitude"] == str(location.latitude)
lon = request_data.json_parameters["longitude"] == str(location.longitude) lon = request_data.json_parameters["longitude"] == str(location.longitude)
return lat and lon return lat and lon
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_location(location=location, chat_id=chat_id) assert await offline_bot.send_location(location=location, chat_id=chat_id)
async def test_edit_live_location_with_location(self, monkeypatch, bot, location): async def test_edit_live_location_with_location(self, monkeypatch, offline_bot, location):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
lat = request_data.json_parameters["latitude"] == str(location.latitude) lat = request_data.json_parameters["latitude"] == str(location.latitude)
lon = request_data.json_parameters["longitude"] == str(location.longitude) lon = request_data.json_parameters["longitude"] == str(location.longitude)
return lat and lon return lat and lon
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.edit_message_live_location(None, None, location=location) assert await offline_bot.edit_message_live_location(None, None, location=location)
@pytest.mark.parametrize( @pytest.mark.parametrize(
("default_bot", "custom"), ("default_bot", "custom"),

View file

@ -105,7 +105,7 @@ class TestPhotoWithoutRequest(PhotoTestBase):
# so far # so far
assert thumb.file_size in [1475, 1477] assert thumb.file_size in [1475, 1477]
def test_de_json(self, bot, photo): def test_de_json(self, offline_bot, photo):
json_dict = { json_dict = {
"file_id": photo.file_id, "file_id": photo.file_id,
"file_unique_id": photo.file_unique_id, "file_unique_id": photo.file_unique_id,
@ -113,7 +113,7 @@ class TestPhotoWithoutRequest(PhotoTestBase):
"height": self.height, "height": self.height,
"file_size": self.file_size, "file_size": self.file_size,
} }
json_photo = PhotoSize.de_json(json_dict, bot) json_photo = PhotoSize.de_json(json_dict, offline_bot)
assert json_photo.api_kwargs == {} assert json_photo.api_kwargs == {}
assert json_photo.file_id == photo.file_id assert json_photo.file_id == photo.file_id
@ -160,22 +160,22 @@ class TestPhotoWithoutRequest(PhotoTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_error_without_required_args(self, bot, chat_id): async def test_error_without_required_args(self, offline_bot, chat_id):
with pytest.raises(TypeError): with pytest.raises(TypeError):
await bot.send_photo(chat_id=chat_id) await offline_bot.send_photo(chat_id=chat_id)
async def test_send_photo_custom_filename(self, bot, chat_id, photo_file, monkeypatch): async def test_send_photo_custom_filename(self, offline_bot, chat_id, photo_file, monkeypatch):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" return next(iter(request_data.multipart_data.values()))[0] == "custom_filename"
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_photo(chat_id, photo_file, filename="custom_filename") assert await offline_bot.send_photo(chat_id, photo_file, filename="custom_filename")
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_photo_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_photo_local_files(self, monkeypatch, offline_bot, chat_id, local_mode):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -187,18 +187,18 @@ class TestPhotoWithoutRequest(PhotoTestBase):
else: else:
test_flag = isinstance(data.get("photo"), InputFile) test_flag = isinstance(data.get("photo"), InputFile)
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_photo(chat_id, file) await offline_bot.send_photo(chat_id, file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_send_with_photosize(self, monkeypatch, bot, chat_id, photo): async def test_send_with_photosize(self, monkeypatch, offline_bot, chat_id, photo):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["photo"] == photo.file_id return request_data.json_parameters["photo"] == photo.file_id
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_photo(photo=photo, chat_id=chat_id) assert await offline_bot.send_photo(photo=photo, chat_id=chat_id)
async def test_get_file_instance_method(self, monkeypatch, photo): async def test_get_file_instance_method(self, monkeypatch, photo):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -165,7 +165,7 @@ class TestStickerWithoutRequest(StickerTestBase):
assert sticker_dict["type"] == sticker.type assert sticker_dict["type"] == sticker.type
assert sticker_dict["needs_repainting"] == sticker.needs_repainting assert sticker_dict["needs_repainting"] == sticker.needs_repainting
def test_de_json(self, bot, sticker): def test_de_json(self, offline_bot, sticker):
json_dict = { json_dict = {
"file_id": self.sticker_file_id, "file_id": self.sticker_file_id,
"file_unique_id": self.sticker_file_unique_id, "file_unique_id": self.sticker_file_unique_id,
@ -181,7 +181,7 @@ class TestStickerWithoutRequest(StickerTestBase):
"custom_emoji_id": self.custom_emoji_id, "custom_emoji_id": self.custom_emoji_id,
"needs_repainting": self.needs_repainting, "needs_repainting": self.needs_repainting,
} }
json_sticker = Sticker.de_json(json_dict, bot) json_sticker = Sticker.de_json(json_dict, offline_bot)
assert json_sticker.api_kwargs == {} assert json_sticker.api_kwargs == {}
assert json_sticker.file_id == self.sticker_file_id assert json_sticker.file_id == self.sticker_file_id
@ -284,22 +284,22 @@ class TestStickerWithoutRequest(StickerTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_error_without_required_args(self, bot, chat_id): async def test_error_without_required_args(self, offline_bot, chat_id):
with pytest.raises(TypeError): with pytest.raises(TypeError):
await bot.send_sticker(chat_id) await offline_bot.send_sticker(chat_id)
async def test_send_with_sticker(self, monkeypatch, bot, chat_id, sticker): async def test_send_with_sticker(self, monkeypatch, offline_bot, chat_id, sticker):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["sticker"] == sticker.file_id return request_data.json_parameters["sticker"] == sticker.file_id
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_sticker(sticker=sticker, chat_id=chat_id) assert await offline_bot.send_sticker(sticker=sticker, chat_id=chat_id)
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_sticker_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_sticker_local_files(self, monkeypatch, offline_bot, chat_id, local_mode):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -311,11 +311,11 @@ class TestStickerWithoutRequest(StickerTestBase):
else: else:
test_flag = isinstance(data.get("sticker"), InputFile) test_flag = isinstance(data.get("sticker"), InputFile)
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_sticker(chat_id, file) await offline_bot.send_sticker(chat_id, file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
@pytest.mark.parametrize( @pytest.mark.parametrize(
("default_bot", "custom"), ("default_bot", "custom"),
@ -587,8 +587,8 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, sticker): def test_de_json(self, offline_bot, sticker):
name = f"test_by_{bot.username}" name = f"test_by_{offline_bot.username}"
json_dict = { json_dict = {
"name": name, "name": name,
"title": self.title, "title": self.title,
@ -597,7 +597,7 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
"sticker_type": self.sticker_type, "sticker_type": self.sticker_type,
"contains_masks": self.contains_masks, "contains_masks": self.contains_masks,
} }
sticker_set = StickerSet.de_json(json_dict, bot) sticker_set = StickerSet.de_json(json_dict, offline_bot)
assert sticker_set.name == name assert sticker_set.name == name
assert sticker_set.title == self.title assert sticker_set.title == self.title
@ -653,11 +653,11 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_upload_sticker_file_local_files( async def test_upload_sticker_file_local_files(
self, monkeypatch, bot, chat_id, local_mode, recwarn self, monkeypatch, offline_bot, chat_id, local_mode, recwarn
): ):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -670,24 +670,24 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
else isinstance(data.get("sticker"), InputFile) else isinstance(data.get("sticker"), InputFile)
) )
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.upload_sticker_file( await offline_bot.upload_sticker_file(
chat_id, sticker=file, sticker_format=StickerFormat.STATIC chat_id, sticker=file, sticker_format=StickerFormat.STATIC
) )
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_create_new_sticker_set_local_files( async def test_create_new_sticker_set_local_files(
self, self,
monkeypatch, monkeypatch,
bot, offline_bot,
chat_id, chat_id,
local_mode, local_mode,
): ):
monkeypatch.setattr(bot, "_local_mode", local_mode) monkeypatch.setattr(offline_bot, "_local_mode", local_mode)
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
# always assumed to be local mode because we don't have access to local_mode setting # always assumed to be local mode because we don't have access to local_mode setting
@ -698,8 +698,8 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
nonlocal test_flag nonlocal test_flag
test_flag = data.get("stickers")[0].sticker == expected test_flag = data.get("stickers")[0].sticker == expected
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.create_new_sticker_set( await offline_bot.create_new_sticker_set(
chat_id, chat_id,
"name", "name",
"title", "title",
@ -707,7 +707,9 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
) )
assert test_flag assert test_flag
async def test_create_new_sticker_all_params(self, monkeypatch, bot, chat_id, mask_position): async def test_create_new_sticker_all_params(
self, monkeypatch, offline_bot, chat_id, mask_position
):
async def make_assertion(_, data, *args, **kwargs): async def make_assertion(_, data, *args, **kwargs):
assert data["user_id"] == chat_id assert data["user_id"] == chat_id
assert data["name"] == "name" assert data["name"] == "name"
@ -715,8 +717,8 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
assert data["stickers"] == ["wow.png", "wow.tgs", "wow.webp"] assert data["stickers"] == ["wow.png", "wow.tgs", "wow.webp"]
assert data["needs_repainting"] is True assert data["needs_repainting"] is True
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.create_new_sticker_set( await offline_bot.create_new_sticker_set(
chat_id, chat_id,
"name", "name",
"title", "title",
@ -725,9 +727,11 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
) )
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_add_sticker_to_set_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_add_sticker_to_set_local_files(
monkeypatch.setattr(bot, "_local_mode", local_mode) self, monkeypatch, offline_bot, chat_id, local_mode
# For just test that the correct paths are passed as we have no local bot API set up ):
monkeypatch.setattr(offline_bot, "_local_mode", local_mode)
# For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
# always assumed to be local mode because we don't have access to local_mode setting # always assumed to be local mode because we don't have access to local_mode setting
@ -738,8 +742,8 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
nonlocal test_flag nonlocal test_flag
test_flag = data.get("sticker").sticker == expected test_flag = data.get("sticker").sticker == expected
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.add_sticker_to_set( await offline_bot.add_sticker_to_set(
chat_id, chat_id,
"name", "name",
sticker=InputSticker(sticker=file, emoji_list=["this"], format="static"), sticker=InputSticker(sticker=file, emoji_list=["this"], format="static"),
@ -748,11 +752,11 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_set_sticker_set_thumbnail_local_files( async def test_set_sticker_set_thumbnail_local_files(
self, monkeypatch, bot, chat_id, local_mode self, monkeypatch, offline_bot, chat_id, local_mode
): ):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -764,11 +768,13 @@ class TestStickerSetWithoutRequest(StickerSetTestBase):
else: else:
test_flag = isinstance(data.get("thumbnail"), InputFile) test_flag = isinstance(data.get("thumbnail"), InputFile)
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.set_sticker_set_thumbnail("name", chat_id, thumbnail=file, format="static") await offline_bot.set_sticker_set_thumbnail(
"name", chat_id, thumbnail=file, format="static"
)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_get_file_instance_method(self, monkeypatch, sticker): async def test_get_file_instance_method(self, monkeypatch, sticker):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):
@ -1085,14 +1091,14 @@ class TestMaskPositionWithoutRequest(MaskPositionTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_mask_position_de_json(self, bot): def test_mask_position_de_json(self, offline_bot):
json_dict = { json_dict = {
"point": self.point, "point": self.point,
"x_shift": self.x_shift, "x_shift": self.x_shift,
"y_shift": self.y_shift, "y_shift": self.y_shift,
"scale": self.scale, "scale": self.scale,
} }
mask_position = MaskPosition.de_json(json_dict, bot) mask_position = MaskPosition.de_json(json_dict, offline_bot)
assert mask_position.api_kwargs == {} assert mask_position.api_kwargs == {}
assert mask_position.point == self.point assert mask_position.point == self.point

View file

@ -57,7 +57,7 @@ class TestVenueWithoutRequest(VenueTestBase):
assert getattr(venue, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(venue, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(venue)) == len(set(mro_slots(venue))), "duplicate slot" assert len(mro_slots(venue)) == len(set(mro_slots(venue))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"location": self.location.to_dict(), "location": self.location.to_dict(),
"title": self.title, "title": self.title,
@ -67,7 +67,7 @@ class TestVenueWithoutRequest(VenueTestBase):
"google_place_id": self.google_place_id, "google_place_id": self.google_place_id,
"google_place_type": self.google_place_type, "google_place_type": self.google_place_type,
} }
venue = Venue.de_json(json_dict, bot) venue = Venue.de_json(json_dict, offline_bot)
assert venue.api_kwargs == {} assert venue.api_kwargs == {}
assert venue.location == self.location assert venue.location == self.location
@ -110,13 +110,13 @@ class TestVenueWithoutRequest(VenueTestBase):
assert a != d2 assert a != d2
assert hash(a) != hash(d2) assert hash(a) != hash(d2)
async def test_send_venue_without_required(self, bot, chat_id): async def test_send_venue_without_required(self, offline_bot, chat_id):
with pytest.raises(ValueError, match="Either venue or latitude, longitude, address and"): with pytest.raises(ValueError, match="Either venue or latitude, longitude, address and"):
await bot.send_venue(chat_id=chat_id) await offline_bot.send_venue(chat_id=chat_id)
async def test_send_venue_mutually_exclusive(self, bot, chat_id, venue): async def test_send_venue_mutually_exclusive(self, offline_bot, chat_id, venue):
with pytest.raises(ValueError, match="Not both"): with pytest.raises(ValueError, match="Not both"):
await bot.send_venue( await offline_bot.send_venue(
chat_id=chat_id, chat_id=chat_id,
latitude=1, latitude=1,
longitude=1, longitude=1,
@ -125,7 +125,7 @@ class TestVenueWithoutRequest(VenueTestBase):
venue=venue, venue=venue,
) )
async def test_send_with_venue(self, monkeypatch, bot, chat_id, venue): async def test_send_with_venue(self, monkeypatch, offline_bot, chat_id, venue):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters data = request_data.json_parameters
return ( return (
@ -139,8 +139,8 @@ class TestVenueWithoutRequest(VenueTestBase):
and data["google_place_type"] == self.google_place_type and data["google_place_type"] == self.google_place_type
) )
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
message = await bot.send_venue(chat_id, venue=venue) message = await offline_bot.send_venue(chat_id, venue=venue)
assert message assert message
@pytest.mark.parametrize( @pytest.mark.parametrize(

View file

@ -93,7 +93,7 @@ class TestVideoWithoutRequest(VideoTestBase):
assert video.file_size == self.file_size assert video.file_size == self.file_size
assert video.mime_type == self.mime_type assert video.mime_type == self.mime_type
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"file_id": self.video_file_id, "file_id": self.video_file_id,
"file_unique_id": self.video_file_unique_id, "file_unique_id": self.video_file_unique_id,
@ -104,7 +104,7 @@ class TestVideoWithoutRequest(VideoTestBase):
"file_size": self.file_size, "file_size": self.file_size,
"file_name": self.file_name, "file_name": self.file_name,
} }
json_video = Video.de_json(json_dict, bot) json_video = Video.de_json(json_dict, offline_bot)
assert json_video.api_kwargs == {} assert json_video.api_kwargs == {}
assert json_video.file_id == self.video_file_id assert json_video.file_id == self.video_file_id
@ -149,30 +149,30 @@ class TestVideoWithoutRequest(VideoTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_error_without_required_args(self, bot, chat_id): async def test_error_without_required_args(self, offline_bot, chat_id):
with pytest.raises(TypeError): with pytest.raises(TypeError):
await bot.send_video(chat_id=chat_id) await offline_bot.send_video(chat_id=chat_id)
async def test_send_with_video(self, monkeypatch, bot, chat_id, video): async def test_send_with_video(self, monkeypatch, offline_bot, chat_id, video):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["video"] == video.file_id return request_data.json_parameters["video"] == video.file_id
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_video(chat_id, video=video) assert await offline_bot.send_video(chat_id, video=video)
async def test_send_video_custom_filename(self, bot, chat_id, video_file, monkeypatch): async def test_send_video_custom_filename(self, offline_bot, chat_id, video_file, monkeypatch):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" return next(iter(request_data.multipart_data.values()))[0] == "custom_filename"
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_video(chat_id, video_file, filename="custom_filename") assert await offline_bot.send_video(chat_id, video_file, filename="custom_filename")
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_video_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_video_local_files(self, monkeypatch, offline_bot, chat_id, local_mode):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -186,11 +186,11 @@ class TestVideoWithoutRequest(VideoTestBase):
data.get("thumbnail"), InputFile data.get("thumbnail"), InputFile
) )
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_video(chat_id, file, thumbnail=file) await offline_bot.send_video(chat_id, file, thumbnail=file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_get_file_instance_method(self, monkeypatch, video): async def test_get_file_instance_method(self, monkeypatch, video):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -85,7 +85,7 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase):
assert video_note.duration == self.duration assert video_note.duration == self.duration
assert video_note.file_size == self.file_size assert video_note.file_size == self.file_size
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"file_id": self.videonote_file_id, "file_id": self.videonote_file_id,
"file_unique_id": self.videonote_file_unique_id, "file_unique_id": self.videonote_file_unique_id,
@ -93,7 +93,7 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase):
"duration": self.duration, "duration": self.duration,
"file_size": self.file_size, "file_size": self.file_size,
} }
json_video_note = VideoNote.de_json(json_dict, bot) json_video_note = VideoNote.de_json(json_dict, offline_bot)
assert json_video_note.api_kwargs == {} assert json_video_note.api_kwargs == {}
assert json_video_note.file_id == self.videonote_file_id assert json_video_note.file_id == self.videonote_file_id
@ -132,32 +132,36 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_error_without_required_args(self, bot, chat_id): async def test_error_without_required_args(self, offline_bot, chat_id):
with pytest.raises(TypeError): with pytest.raises(TypeError):
await bot.send_video_note(chat_id=chat_id) await offline_bot.send_video_note(chat_id=chat_id)
async def test_send_with_video_note(self, monkeypatch, bot, chat_id, video_note): async def test_send_with_video_note(self, monkeypatch, offline_bot, chat_id, video_note):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["video_note"] == video_note.file_id return request_data.json_parameters["video_note"] == video_note.file_id
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_video_note(chat_id, video_note=video_note) assert await offline_bot.send_video_note(chat_id, video_note=video_note)
async def test_send_video_note_custom_filename( async def test_send_video_note_custom_filename(
self, bot, chat_id, video_note_file, monkeypatch self, offline_bot, chat_id, video_note_file, monkeypatch
): ):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" return next(iter(request_data.multipart_data.values()))[0] == "custom_filename"
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_video_note(chat_id, video_note_file, filename="custom_filename") assert await offline_bot.send_video_note(
chat_id, video_note_file, filename="custom_filename"
)
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_video_note_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_video_note_local_files(
self, monkeypatch, offline_bot, chat_id, local_mode
):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -173,11 +177,11 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase):
data.get("thumbnail"), InputFile data.get("thumbnail"), InputFile
) )
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_video_note(chat_id, file, thumbnail=file) await offline_bot.send_video_note(chat_id, file, thumbnail=file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_get_file_instance_method(self, monkeypatch, video_note): async def test_get_file_instance_method(self, monkeypatch, video_note):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -78,7 +78,7 @@ class TestVoiceWithoutRequest(VoiceTestBase):
assert voice.mime_type == self.mime_type assert voice.mime_type == self.mime_type
assert voice.file_size == self.file_size assert voice.file_size == self.file_size
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"file_id": self.voice_file_id, "file_id": self.voice_file_id,
"file_unique_id": self.voice_file_unique_id, "file_unique_id": self.voice_file_unique_id,
@ -86,7 +86,7 @@ class TestVoiceWithoutRequest(VoiceTestBase):
"mime_type": self.mime_type, "mime_type": self.mime_type,
"file_size": self.file_size, "file_size": self.file_size,
} }
json_voice = Voice.de_json(json_dict, bot) json_voice = Voice.de_json(json_dict, offline_bot)
assert json_voice.api_kwargs == {} assert json_voice.api_kwargs == {}
assert json_voice.file_id == self.voice_file_id assert json_voice.file_id == self.voice_file_id
@ -125,30 +125,30 @@ class TestVoiceWithoutRequest(VoiceTestBase):
assert a != e assert a != e
assert hash(a) != hash(e) assert hash(a) != hash(e)
async def test_error_without_required_args(self, bot, chat_id): async def test_error_without_required_args(self, offline_bot, chat_id):
with pytest.raises(TypeError): with pytest.raises(TypeError):
await bot.sendVoice(chat_id) await offline_bot.sendVoice(chat_id)
async def test_send_voice_custom_filename(self, bot, chat_id, voice_file, monkeypatch): async def test_send_voice_custom_filename(self, offline_bot, chat_id, voice_file, monkeypatch):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" return next(iter(request_data.multipart_data.values()))[0] == "custom_filename"
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_voice(chat_id, voice_file, filename="custom_filename") assert await offline_bot.send_voice(chat_id, voice_file, filename="custom_filename")
async def test_send_with_voice(self, monkeypatch, bot, chat_id, voice): async def test_send_with_voice(self, monkeypatch, offline_bot, chat_id, voice):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["voice"] == voice.file_id return request_data.json_parameters["voice"] == voice.file_id
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_voice(chat_id, voice=voice) assert await offline_bot.send_voice(chat_id, voice=voice)
@pytest.mark.parametrize("local_mode", [True, False]) @pytest.mark.parametrize("local_mode", [True, False])
async def test_send_voice_local_files(self, monkeypatch, bot, chat_id, local_mode): async def test_send_voice_local_files(self, monkeypatch, offline_bot, chat_id, local_mode):
try: try:
bot._local_mode = local_mode offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local bot API set up # For just test that the correct paths are passed as we have no local Bot API set up
test_flag = False test_flag = False
file = data_file("telegram.jpg") file = data_file("telegram.jpg")
expected = file.as_uri() expected = file.as_uri()
@ -160,11 +160,11 @@ class TestVoiceWithoutRequest(VoiceTestBase):
else: else:
test_flag = isinstance(data.get("voice"), InputFile) test_flag = isinstance(data.get("voice"), InputFile)
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
await bot.send_voice(chat_id, file) await offline_bot.send_voice(chat_id, file)
assert test_flag assert test_flag
finally: finally:
bot._local_mode = False offline_bot._local_mode = False
async def test_get_file_instance_method(self, monkeypatch, voice): async def test_get_file_instance_method(self, monkeypatch, voice):
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -55,20 +55,20 @@ class TestGameWithoutRequest(GameTestBase):
assert getattr(game, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(game, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(game)) == len(set(mro_slots(game))), "duplicate slot" assert len(mro_slots(game)) == len(set(mro_slots(game))), "duplicate slot"
def test_de_json_required(self, bot): def test_de_json_required(self, offline_bot):
json_dict = { json_dict = {
"title": self.title, "title": self.title,
"description": self.description, "description": self.description,
"photo": [self.photo[0].to_dict()], "photo": [self.photo[0].to_dict()],
} }
game = Game.de_json(json_dict, bot) game = Game.de_json(json_dict, offline_bot)
assert game.api_kwargs == {} assert game.api_kwargs == {}
assert game.title == self.title assert game.title == self.title
assert game.description == self.description assert game.description == self.description
assert game.photo == tuple(self.photo) assert game.photo == tuple(self.photo)
def test_de_json_all(self, bot): def test_de_json_all(self, offline_bot):
json_dict = { json_dict = {
"title": self.title, "title": self.title,
"description": self.description, "description": self.description,
@ -77,7 +77,7 @@ class TestGameWithoutRequest(GameTestBase):
"text_entities": [self.text_entities[0].to_dict()], "text_entities": [self.text_entities[0].to_dict()],
"animation": self.animation.to_dict(), "animation": self.animation.to_dict(),
} }
game = Game.de_json(json_dict, bot) game = Game.de_json(json_dict, offline_bot)
assert game.api_kwargs == {} assert game.api_kwargs == {}
assert game.title == self.title assert game.title == self.title

View file

@ -42,20 +42,20 @@ class TestGameHighScoreWithoutRequest(GameHighScoreTestBase):
assert getattr(game_highscore, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(game_highscore, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(game_highscore)) == len(set(mro_slots(game_highscore))), "same slot" assert len(mro_slots(game_highscore)) == len(set(mro_slots(game_highscore))), "same slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"position": self.position, "position": self.position,
"user": self.user.to_dict(), "user": self.user.to_dict(),
"score": self.score, "score": self.score,
} }
highscore = GameHighScore.de_json(json_dict, bot) highscore = GameHighScore.de_json(json_dict, offline_bot)
assert highscore.api_kwargs == {} assert highscore.api_kwargs == {}
assert highscore.position == self.position assert highscore.position == self.position
assert highscore.user == self.user assert highscore.user == self.user
assert highscore.score == self.score assert highscore.score == self.score
assert GameHighScore.de_json(None, bot) is None assert GameHighScore.de_json(None, offline_bot) is None
def test_to_dict(self, game_highscore): def test_to_dict(self, game_highscore):
game_highscore_dict = game_highscore.to_dict() game_highscore_dict = game_highscore.to_dict()

View file

@ -116,7 +116,7 @@ class TestInlineKeyboardButtonWithoutRequest(InlineKeyboardButtonTestBase):
== inline_keyboard_button.switch_inline_query_chosen_chat.to_dict() == inline_keyboard_button.switch_inline_query_chosen_chat.to_dict()
) )
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"text": self.text, "text": self.text,
"url": self.url, "url": self.url,
@ -150,7 +150,7 @@ class TestInlineKeyboardButtonWithoutRequest(InlineKeyboardButtonTestBase):
== self.switch_inline_query_chosen_chat == self.switch_inline_query_chosen_chat
) )
none = InlineKeyboardButton.de_json({}, bot) none = InlineKeyboardButton.de_json({}, offline_bot)
assert none is None assert none is None
def test_equality(self): def test_equality(self):

View file

@ -192,7 +192,9 @@ class TestInlineKeyboardMarkupWithoutRequest(InlineKeyboardMarkupTestBase):
with pytest.raises(ValueError, match="should be a sequence of sequences"): with pytest.raises(ValueError, match="should be a sequence of sequences"):
InlineKeyboardMarkup([[[InlineKeyboardButton("only_2d_array_is_allowed", "1")]]]) InlineKeyboardMarkup([[[InlineKeyboardButton("only_2d_array_is_allowed", "1")]]])
async def test_expected_values_empty_switch(self, inline_keyboard_markup, bot, monkeypatch): async def test_expected_values_empty_switch(
self, inline_keyboard_markup, offline_bot, monkeypatch
):
async def make_assertion( async def make_assertion(
url, url,
data, data,
@ -224,8 +226,8 @@ class TestInlineKeyboardMarkupWithoutRequest(InlineKeyboardMarkupTestBase):
inline_keyboard_markup.inline_keyboard[0][1].callback_data = None inline_keyboard_markup.inline_keyboard[0][1].callback_data = None
inline_keyboard_markup.inline_keyboard[0][1].switch_inline_query_current_chat = "" inline_keyboard_markup.inline_keyboard[0][1].switch_inline_query_current_chat = ""
monkeypatch.setattr(bot, "_send_message", make_assertion) monkeypatch.setattr(offline_bot, "_send_message", make_assertion)
await bot.send_message(123, "test", reply_markup=inline_keyboard_markup) await offline_bot.send_message(123, "test", reply_markup=inline_keyboard_markup)
class TestInlineKeyborardMarkupWithRequest(InlineKeyboardMarkupTestBase): class TestInlineKeyborardMarkupWithRequest(InlineKeyboardMarkupTestBase):

View file

@ -55,7 +55,7 @@ class TestInlineQueryWithoutRequest(InlineQueryTestBase):
assert getattr(inline_query, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inline_query, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inline_query)) == len(set(mro_slots(inline_query))), "duplicate slot" assert len(mro_slots(inline_query)) == len(set(mro_slots(inline_query))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"from": self.from_user.to_dict(), "from": self.from_user.to_dict(),
@ -63,7 +63,7 @@ class TestInlineQueryWithoutRequest(InlineQueryTestBase):
"offset": self.offset, "offset": self.offset,
"location": self.location.to_dict(), "location": self.location.to_dict(),
} }
inline_query_json = InlineQuery.de_json(json_dict, bot) inline_query_json = InlineQuery.de_json(json_dict, offline_bot)
assert inline_query_json.api_kwargs == {} assert inline_query_json.api_kwargs == {}
assert inline_query_json.id == self.id_ assert inline_query_json.id == self.id_

View file

@ -203,8 +203,8 @@ class TestInputInvoiceMessageContentWithoutRequest(InputInvoiceMessageContentTes
== input_invoice_message_content.is_flexible == input_invoice_message_content.is_flexible
) )
def test_de_json(self, bot): def test_de_json(self, offline_bot):
assert InputInvoiceMessageContent.de_json({}, bot=bot) is None assert InputInvoiceMessageContent.de_json({}, bot=offline_bot) is None
json_dict = { json_dict = {
"title": self.title, "title": self.title,
@ -229,7 +229,9 @@ class TestInputInvoiceMessageContentWithoutRequest(InputInvoiceMessageContentTes
"is_flexible": self.is_flexible, "is_flexible": self.is_flexible,
} }
input_invoice_message_content = InputInvoiceMessageContent.de_json(json_dict, bot=bot) input_invoice_message_content = InputInvoiceMessageContent.de_json(
json_dict, bot=offline_bot
)
assert input_invoice_message_content.api_kwargs == {} assert input_invoice_message_content.api_kwargs == {}
assert input_invoice_message_content.title == self.title assert input_invoice_message_content.title == self.title

View file

@ -28,7 +28,7 @@ with the TEST_WITH_OPT_DEPS environment variable set to False in addition to the
""" """
import pytest import pytest
from telegram import _bot as bot import telegram
from telegram._passport import credentials from telegram._passport import credentials
from tests.auxil.envvars import TEST_WITH_OPT_DEPS from tests.auxil.envvars import TEST_WITH_OPT_DEPS
@ -39,7 +39,7 @@ from tests.auxil.envvars import TEST_WITH_OPT_DEPS
class TestNoPassportWithoutRequest: class TestNoPassportWithoutRequest:
def test_bot_init(self, bot_info): def test_bot_init(self, bot_info):
with pytest.raises(RuntimeError, match="passport"): with pytest.raises(RuntimeError, match="passport"):
bot.Bot(bot_info["token"], private_key=1, private_key_password=2) telegram.Bot(bot_info["token"], private_key=1, private_key_password=2)
def test_credentials_decrypt(self): def test_credentials_decrypt(self):
with pytest.raises(RuntimeError, match="passport"): with pytest.raises(RuntimeError, match="passport"):

View file

@ -390,8 +390,8 @@ class TestPassportWithoutRequest(PassportTestBase):
assert email.type == "email" assert email.type == "email"
assert email.email == "fb3e3i47zt@dispostable.com" assert email.email == "fb3e3i47zt@dispostable.com"
def test_de_json_and_to_dict(self, bot): def test_de_json_and_to_dict(self, offline_bot):
passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot) passport_data = PassportData.de_json(RAW_PASSPORT_DATA, offline_bot)
assert passport_data.api_kwargs == {} assert passport_data.api_kwargs == {}
assert passport_data.to_dict() == RAW_PASSPORT_DATA assert passport_data.to_dict() == RAW_PASSPORT_DATA
@ -414,14 +414,14 @@ class TestPassportWithoutRequest(PassportTestBase):
assert a != c assert a != c
assert hash(a) != hash(c) assert hash(a) != hash(c)
def test_bot_init_invalid_key(self, bot): def test_bot_init_invalid_key(self, offline_bot):
with pytest.raises(TypeError): with pytest.raises(TypeError):
Bot(bot.token, private_key="Invalid key!") Bot(offline_bot.token, private_key="Invalid key!")
with pytest.raises(ValueError, match="Could not deserialize key data"): with pytest.raises(ValueError, match="Could not deserialize key data"):
Bot(bot.token, private_key=b"Invalid key!") Bot(offline_bot.token, private_key=b"Invalid key!")
def test_all_types(self, passport_data, bot, all_passport_data): def test_all_types(self, passport_data, offline_bot, all_passport_data):
credentials = passport_data.decrypted_credentials.to_dict() credentials = passport_data.decrypted_credentials.to_dict()
# Copy credentials from other types to all types so we can decrypt everything # Copy credentials from other types to all types so we can decrypt everything
@ -446,46 +446,46 @@ class TestPassportWithoutRequest(PassportTestBase):
# Replaced below # Replaced below
"credentials": {"data": "data", "hash": "hash", "secret": "secret"}, "credentials": {"data": "data", "hash": "hash", "secret": "secret"},
}, },
bot=bot, bot=offline_bot,
) )
assert new.api_kwargs == {} assert new.api_kwargs == {}
new.credentials._decrypted_data = Credentials.de_json(credentials, bot) new.credentials._decrypted_data = Credentials.de_json(credentials, offline_bot)
assert new.credentials.api_kwargs == {} assert new.credentials.api_kwargs == {}
assert isinstance(new, PassportData) assert isinstance(new, PassportData)
assert new.decrypted_data assert new.decrypted_data
async def test_passport_data_okay_with_non_crypto_bot(self, bot): async def test_passport_data_okay_with_non_crypto_bot(self, offline_bot):
async with make_bot(token=bot.token) as b: async with make_bot(token=offline_bot.token) as b:
assert PassportData.de_json(RAW_PASSPORT_DATA, bot=b) assert PassportData.de_json(RAW_PASSPORT_DATA, bot=b)
def test_wrong_hash(self, bot): def test_wrong_hash(self, offline_bot):
data = deepcopy(RAW_PASSPORT_DATA) data = deepcopy(RAW_PASSPORT_DATA)
data["credentials"]["hash"] = "bm90Y29ycmVjdGhhc2g=" # Not correct hash data["credentials"]["hash"] = "bm90Y29ycmVjdGhhc2g=" # Not correct hash
passport_data = PassportData.de_json(data, bot=bot) passport_data = PassportData.de_json(data, bot=offline_bot)
with pytest.raises(PassportDecryptionError): with pytest.raises(PassportDecryptionError):
assert passport_data.decrypted_data assert passport_data.decrypted_data
async def test_wrong_key(self, bot): async def test_wrong_key(self, offline_bot):
short_key = ( short_key = (
b"-----BEGIN RSA PRIVATE" b"-----BEGIN RSA PRIVATE"
b" KEY-----\r\nMIIBOQIBAAJBAKU+OZ2jJm7sCA/ec4gngNZhXYPu+DZ/TAwSMl0W7vAPXAsLplBk\r\nO8l6IBHx8N0ZC4Bc65mO3b2G8YAzqndyqH8CAwEAAQJAWOx3jQFzeVXDsOaBPdAk\r\nYTncXVeIc6tlfUl9mOLyinSbRNCy1XicOiOZFgH1rRKOGIC1235QmqxFvdecySoY\r\nwQIhAOFeGgeX9CrEPuSsd9+kqUcA2avCwqdQgSdy2qggRFyJAiEAu7QHT8JQSkHU\r\nDELfzrzc24AhjyG0z1DpGZArM8COascCIDK42SboXj3Z2UXiQ0CEcMzYNiVgOisq\r\nBUd5pBi+2mPxAiAM5Z7G/Sv1HjbKrOGh29o0/sXPhtpckEuj5QMC6E0gywIgFY6S\r\nNjwrAA+cMmsgY0O2fAzEKkDc5YiFsiXaGaSS4eA=\r\n-----END" b" KEY-----\r\nMIIBOQIBAAJBAKU+OZ2jJm7sCA/ec4gngNZhXYPu+DZ/TAwSMl0W7vAPXAsLplBk\r\nO8l6IBHx8N0ZC4Bc65mO3b2G8YAzqndyqH8CAwEAAQJAWOx3jQFzeVXDsOaBPdAk\r\nYTncXVeIc6tlfUl9mOLyinSbRNCy1XicOiOZFgH1rRKOGIC1235QmqxFvdecySoY\r\nwQIhAOFeGgeX9CrEPuSsd9+kqUcA2avCwqdQgSdy2qggRFyJAiEAu7QHT8JQSkHU\r\nDELfzrzc24AhjyG0z1DpGZArM8COascCIDK42SboXj3Z2UXiQ0CEcMzYNiVgOisq\r\nBUd5pBi+2mPxAiAM5Z7G/Sv1HjbKrOGh29o0/sXPhtpckEuj5QMC6E0gywIgFY6S\r\nNjwrAA+cMmsgY0O2fAzEKkDc5YiFsiXaGaSS4eA=\r\n-----END"
b" RSA PRIVATE KEY-----" b" RSA PRIVATE KEY-----"
) )
async with make_bot(token=bot.token, private_key=short_key) as b: async with make_bot(token=offline_bot.token, private_key=short_key) as b:
passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b) passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b)
with pytest.raises(PassportDecryptionError): with pytest.raises(PassportDecryptionError):
assert passport_data.decrypted_data assert passport_data.decrypted_data
async with make_bot(token=bot.token, private_key=short_key) as b: async with make_bot(token=offline_bot.token, private_key=short_key) as b:
passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b) passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b)
with pytest.raises(PassportDecryptionError): with pytest.raises(PassportDecryptionError):
assert passport_data.decrypted_data assert passport_data.decrypted_data
async def test_mocked_download_passport_file(self, passport_data, monkeypatch): async def test_mocked_download_passport_file(self, passport_data, monkeypatch):
# The files are not coming from our test bot, therefore the file id is invalid/wrong # The files are not coming from our test offline_bot, therefore the file id is invalid/wrong
# when coming from this bot, so we monkeypatch the call, to make sure that Bot.get_file # when coming from this offline_bot, so we monkeypatch the call, to make sure that Bot.get_file
# at least gets called # at least gets called
# TODO: Actually download a passport file in a test # TODO: Actually download a passport file in a test
selfie = passport_data.decrypted_data[1].selfie selfie = passport_data.decrypted_data[1].selfie
@ -501,7 +501,9 @@ class TestPassportWithoutRequest(PassportTestBase):
assert file._credentials.file_hash == self.driver_license_selfie_credentials_file_hash assert file._credentials.file_hash == self.driver_license_selfie_credentials_file_hash
assert file._credentials.secret == self.driver_license_selfie_credentials_secret assert file._credentials.secret == self.driver_license_selfie_credentials_secret
async def test_mocked_set_passport_data_errors(self, monkeypatch, bot, chat_id, passport_data): async def test_mocked_set_passport_data_errors(
self, monkeypatch, offline_bot, chat_id, passport_data
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters data = request_data.parameters
return ( return (
@ -514,8 +516,8 @@ class TestPassportWithoutRequest(PassportTestBase):
== passport_data.decrypted_credentials.secure_data.driver_license.data.data_hash == passport_data.decrypted_credentials.secure_data.driver_license.data.data_hash
) )
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
message = await bot.set_passport_data_errors( message = await offline_bot.set_passport_data_errors(
chat_id, chat_id,
[ [
PassportElementErrorSelfie( PassportElementErrorSelfie(

View file

@ -58,7 +58,7 @@ class TestInvoiceWithoutRequest(InvoiceTestBase):
assert getattr(invoice, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(invoice, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(invoice)) == len(set(mro_slots(invoice))), "duplicate slot" assert len(mro_slots(invoice)) == len(set(mro_slots(invoice))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
invoice_json = Invoice.de_json( invoice_json = Invoice.de_json(
{ {
"title": self.title, "title": self.title,
@ -67,7 +67,7 @@ class TestInvoiceWithoutRequest(InvoiceTestBase):
"currency": self.currency, "currency": self.currency,
"total_amount": self.total_amount, "total_amount": self.total_amount,
}, },
bot, offline_bot,
) )
assert invoice_json.api_kwargs == {} assert invoice_json.api_kwargs == {}
@ -87,15 +87,15 @@ class TestInvoiceWithoutRequest(InvoiceTestBase):
assert invoice_dict["currency"] == invoice.currency assert invoice_dict["currency"] == invoice.currency
assert invoice_dict["total_amount"] == invoice.total_amount assert invoice_dict["total_amount"] == invoice.total_amount
async def test_send_invoice_all_args_mock(self, bot, monkeypatch): async def test_send_invoice_all_args_mock(self, offline_bot, monkeypatch):
# We do this one as safety guard to make sure that we pass all of the optional # We do this one as safety guard to make sure that we pass all of the optional
# parameters correctly because #2526 went unnoticed for 3 years … # parameters correctly because #2526 went unnoticed for 3 years …
async def make_assertion(*args, **_): async def make_assertion(*args, **_):
kwargs = args[1] kwargs = args[1]
return all(kwargs[key] == key for key in kwargs) return all(kwargs[key] == key for key in kwargs)
monkeypatch.setattr(bot, "_send_message", make_assertion) monkeypatch.setattr(offline_bot, "_send_message", make_assertion)
assert await bot.send_invoice( assert await offline_bot.send_invoice(
chat_id="chat_id", chat_id="chat_id",
title="title", title="title",
description="description", description="description",
@ -122,13 +122,13 @@ class TestInvoiceWithoutRequest(InvoiceTestBase):
protect_content=True, protect_content=True,
) )
async def test_send_all_args_create_invoice_link(self, bot, monkeypatch): async def test_send_all_args_create_invoice_link(self, offline_bot, monkeypatch):
async def make_assertion(*args, **_): async def make_assertion(*args, **_):
kwargs = args[1] kwargs = args[1]
return all(kwargs[i] == i for i in kwargs) return all(kwargs[i] == i for i in kwargs)
monkeypatch.setattr(bot, "_post", make_assertion) monkeypatch.setattr(offline_bot, "_post", make_assertion)
assert await bot.create_invoice_link( assert await offline_bot.create_invoice_link(
title="title", title="title",
description="description", description="description",
payload="payload", payload="payload",
@ -151,13 +151,15 @@ class TestInvoiceWithoutRequest(InvoiceTestBase):
is_flexible="is_flexible", is_flexible="is_flexible",
) )
async def test_send_object_as_provider_data(self, monkeypatch, bot, chat_id, provider_token): async def test_send_object_as_provider_data(
self, monkeypatch, offline_bot, chat_id, provider_token
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters["provider_data"] == '{"test_data": 123456789}' return request_data.json_parameters["provider_data"] == '{"test_data": 123456789}'
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.send_invoice( assert await offline_bot.send_invoice(
chat_id, chat_id,
self.title, self.title,
self.description, self.description,

View file

@ -45,14 +45,14 @@ class TestOrderInfoWithoutRequest(OrderInfoTestBase):
assert getattr(order_info, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(order_info, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(order_info)) == len(set(mro_slots(order_info))), "duplicate slot" assert len(mro_slots(order_info)) == len(set(mro_slots(order_info))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"name": self.name, "name": self.name,
"phone_number": self.phone_number, "phone_number": self.phone_number,
"email": self.email, "email": self.email,
"shipping_address": self.shipping_address.to_dict(), "shipping_address": self.shipping_address.to_dict(),
} }
order_info = OrderInfo.de_json(json_dict, bot) order_info = OrderInfo.de_json(json_dict, offline_bot)
assert order_info.api_kwargs == {} assert order_info.api_kwargs == {}
assert order_info.name == self.name assert order_info.name == self.name

View file

@ -60,7 +60,7 @@ class TestPreCheckoutQueryWithoutRequest(PreCheckoutQueryTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"invoice_payload": self.invoice_payload, "invoice_payload": self.invoice_payload,
@ -70,10 +70,10 @@ class TestPreCheckoutQueryWithoutRequest(PreCheckoutQueryTestBase):
"from": self.from_user.to_dict(), "from": self.from_user.to_dict(),
"order_info": self.order_info.to_dict(), "order_info": self.order_info.to_dict(),
} }
pre_checkout_query = PreCheckoutQuery.de_json(json_dict, bot) pre_checkout_query = PreCheckoutQuery.de_json(json_dict, offline_bot)
assert pre_checkout_query.api_kwargs == {} assert pre_checkout_query.api_kwargs == {}
assert pre_checkout_query.get_bot() is bot assert pre_checkout_query.get_bot() is offline_bot
assert pre_checkout_query.id == self.id_ assert pre_checkout_query.id == self.id_
assert pre_checkout_query.invoice_payload == self.invoice_payload assert pre_checkout_query.invoice_payload == self.invoice_payload
assert pre_checkout_query.shipping_option_id == self.shipping_option_id assert pre_checkout_query.shipping_option_id == self.shipping_option_id

View file

@ -48,7 +48,7 @@ class TestRefundedPaymentWithoutRequest(RefundedPaymentTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"invoice_payload": self.invoice_payload, "invoice_payload": self.invoice_payload,
"currency": self.currency, "currency": self.currency,
@ -56,7 +56,7 @@ class TestRefundedPaymentWithoutRequest(RefundedPaymentTestBase):
"telegram_payment_charge_id": self.telegram_payment_charge_id, "telegram_payment_charge_id": self.telegram_payment_charge_id,
"provider_payment_charge_id": self.provider_payment_charge_id, "provider_payment_charge_id": self.provider_payment_charge_id,
} }
refunded_payment = RefundedPayment.de_json(json_dict, bot) refunded_payment = RefundedPayment.de_json(json_dict, offline_bot)
assert refunded_payment.api_kwargs == {} assert refunded_payment.api_kwargs == {}
assert refunded_payment.invoice_payload == self.invoice_payload assert refunded_payment.invoice_payload == self.invoice_payload

View file

@ -50,7 +50,7 @@ class TestShippingAddressWithoutRequest(ShippingAddressTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"country_code": self.country_code, "country_code": self.country_code,
"state": self.state, "state": self.state,
@ -59,7 +59,7 @@ class TestShippingAddressWithoutRequest(ShippingAddressTestBase):
"street_line2": self.street_line2, "street_line2": self.street_line2,
"post_code": self.post_code, "post_code": self.post_code,
} }
shipping_address = ShippingAddress.de_json(json_dict, bot) shipping_address = ShippingAddress.de_json(json_dict, offline_bot)
assert shipping_address.api_kwargs == {} assert shipping_address.api_kwargs == {}
assert shipping_address.country_code == self.country_code assert shipping_address.country_code == self.country_code

View file

@ -54,21 +54,21 @@ class TestShippingQueryWithoutRequest(ShippingQueryTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"invoice_payload": self.invoice_payload, "invoice_payload": self.invoice_payload,
"from": self.from_user.to_dict(), "from": self.from_user.to_dict(),
"shipping_address": self.shipping_address.to_dict(), "shipping_address": self.shipping_address.to_dict(),
} }
shipping_query = ShippingQuery.de_json(json_dict, bot) shipping_query = ShippingQuery.de_json(json_dict, offline_bot)
assert shipping_query.api_kwargs == {} assert shipping_query.api_kwargs == {}
assert shipping_query.id == self.id_ assert shipping_query.id == self.id_
assert shipping_query.invoice_payload == self.invoice_payload assert shipping_query.invoice_payload == self.invoice_payload
assert shipping_query.from_user == self.from_user assert shipping_query.from_user == self.from_user
assert shipping_query.shipping_address == self.shipping_address assert shipping_query.shipping_address == self.shipping_address
assert shipping_query.get_bot() is bot assert shipping_query.get_bot() is offline_bot
def test_to_dict(self, shipping_query): def test_to_dict(self, shipping_query):
shipping_query_dict = shipping_query.to_dict() shipping_query_dict = shipping_query.to_dict()

View file

@ -52,7 +52,7 @@ class TestSuccessfulPaymentWithoutRequest(SuccessfulPaymentTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"invoice_payload": self.invoice_payload, "invoice_payload": self.invoice_payload,
"shipping_option_id": self.shipping_option_id, "shipping_option_id": self.shipping_option_id,
@ -62,7 +62,7 @@ class TestSuccessfulPaymentWithoutRequest(SuccessfulPaymentTestBase):
"telegram_payment_charge_id": self.telegram_payment_charge_id, "telegram_payment_charge_id": self.telegram_payment_charge_id,
"provider_payment_charge_id": self.provider_payment_charge_id, "provider_payment_charge_id": self.provider_payment_charge_id,
} }
successful_payment = SuccessfulPayment.de_json(json_dict, bot) successful_payment = SuccessfulPayment.de_json(json_dict, offline_bot)
assert successful_payment.api_kwargs == {} assert successful_payment.api_kwargs == {}
assert successful_payment.invoice_payload == self.invoice_payload assert successful_payment.invoice_payload == self.invoice_payload

View file

@ -39,9 +39,9 @@ from telegram import (
) )
from telegram.ext import Defaults from telegram.ext import Defaults
from tests.auxil.build_messages import DATE from tests.auxil.build_messages import DATE
from tests.auxil.ci_bots import BOT_INFO_PROVIDER from tests.auxil.ci_bots import BOT_INFO_PROVIDER, JOB_INDEX
from tests.auxil.constants import PRIVATE_KEY from tests.auxil.constants import PRIVATE_KEY
from tests.auxil.envvars import RUN_TEST_OFFICIAL, TEST_WITH_OPT_DEPS from tests.auxil.envvars import GITHUB_ACTION, RUN_TEST_OFFICIAL, TEST_WITH_OPT_DEPS
from tests.auxil.files import data_file from tests.auxil.files import data_file
from tests.auxil.networking import NonchalantHttpxRequest from tests.auxil.networking import NonchalantHttpxRequest
from tests.auxil.pytest_classes import PytestBot, make_bot from tests.auxil.pytest_classes import PytestBot, make_bot
@ -98,6 +98,39 @@ def pytest_collection_modifyitems(items: List[pytest.Item]):
parent.add_marker(pytest.mark.no_req) parent.add_marker(pytest.mark.no_req)
if GITHUB_ACTION and JOB_INDEX == 0:
# let's not slow down the tests too much with these additional checks
# that's why we run them only in GitHub actions and only on *one* of the several test
# matrix entries
@pytest.fixture(autouse=True)
def _disallow_requests_in_without_request_tests(request):
"""This fixture prevents tests that don't require requests from using the online-bot.
This is a sane-effort approach on trying to prevent requests from being made in the
*WithoutRequest classes. Note that we can not prevent all requests, as one can still
manually build a `Bot` object or use `httpx` directly. See #4317 and #4465 for some
discussion.
"""
if type(request).__name__ == "SubRequest":
# Some fixtures used in the *WithoutRequests test classes do use requests, e.g.
# `animation`. Separating that would be too much effort, hence we allow that.
# Unfortunately the `SubRequest` class is not public, so we check only the name for
# less dependency on pytest's internal structure.
return
if not request.cls:
return
name = request.cls.__name__
if not name.endswith("WithoutRequest") or not request.fixturenames:
return
if "bot" in request.fixturenames:
pytest.fail(
f"Test function {request.function} in test class {name} should not have a `bot` "
f"fixture. Use `offline_bot` instead."
)
# Redefine the event_loop fixture to have a session scope. Otherwise `bot` fixture can't be # Redefine the event_loop fixture to have a session scope. Otherwise `bot` fixture can't be
# session. See https://github.com/pytest-dev/pytest-asyncio/issues/68 for more details. # session. See https://github.com/pytest-dev/pytest-asyncio/issues/68 for more details.
@pytest.fixture(scope="session") @pytest.fixture(scope="session")

View file

@ -84,7 +84,7 @@ async def httpx_request():
TEST_WITH_OPT_DEPS, reason="Only relevant if the optional dependency is not installed" TEST_WITH_OPT_DEPS, reason="Only relevant if the optional dependency is not installed"
) )
class TestNoSocksHTTP2WithoutRequest: class TestNoSocksHTTP2WithoutRequest:
async def test_init(self, bot): async def test_init(self, offline_bot):
with pytest.raises(RuntimeError, match=r"python-telegram-bot\[socks\]"): with pytest.raises(RuntimeError, match=r"python-telegram-bot\[socks\]"):
HTTPXRequest(proxy="socks5://foo") HTTPXRequest(proxy="socks5://foo")
with pytest.raises(RuntimeError, match=r"python-telegram-bot\[http2\]"): with pytest.raises(RuntimeError, match=r"python-telegram-bot\[http2\]"):
@ -546,28 +546,10 @@ class TestHTTPXRequestWithoutRequest:
assert self.test_flag["init"] == 1 assert self.test_flag["init"] == 1
assert self.test_flag["shutdown"] == 1 assert self.test_flag["shutdown"] == 1
async def test_multiple_init_cycles(self):
# nothing really to assert - this should just not fail
httpx_request = HTTPXRequest()
async with httpx_request:
await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET")
async with httpx_request:
await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET")
async def test_http_version_error(self): async def test_http_version_error(self):
with pytest.raises(ValueError, match="`http_version` must be either"): with pytest.raises(ValueError, match="`http_version` must be either"):
HTTPXRequest(http_version="1.0") HTTPXRequest(http_version="1.0")
async def test_http_1_response(self):
httpx_request = HTTPXRequest(http_version="1.1")
async with httpx_request:
resp = await httpx_request._client.request(
url="https://python-telegram-bot.org",
method="GET",
headers={"User-Agent": httpx_request.USER_AGENT},
)
assert resp.http_version == "HTTP/1.1"
async def test_do_request_after_shutdown(self, httpx_request): async def test_do_request_after_shutdown(self, httpx_request):
await httpx_request.shutdown() await httpx_request.shutdown()
with pytest.raises(RuntimeError, match="not initialized"): with pytest.raises(RuntimeError, match="not initialized"):
@ -831,6 +813,24 @@ class TestHTTPXRequestWithoutRequest:
@pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="No need to run this twice") @pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="No need to run this twice")
class TestHTTPXRequestWithRequest: class TestHTTPXRequestWithRequest:
async def test_multiple_init_cycles(self):
# nothing really to assert - this should just not fail
httpx_request = HTTPXRequest()
async with httpx_request:
await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET")
async with httpx_request:
await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET")
async def test_http_1_response(self):
httpx_request = HTTPXRequest(http_version="1.1")
async with httpx_request:
resp = await httpx_request._client.request(
url="https://python-telegram-bot.org",
method="GET",
headers={"User-Agent": httpx_request.USER_AGENT},
)
assert resp.http_version == "HTTP/1.1"
async def test_do_request_wait_for_pool(self, httpx_request): async def test_do_request_wait_for_pool(self, httpx_request):
"""The pool logic is buried rather deeply in httpxcore, so we make actual requests here """The pool logic is buried rather deeply in httpxcore, so we make actual requests here
instead of mocking""" instead of mocking"""

View file

@ -48,9 +48,9 @@ class TestBirthdateWithoutRequest(BirthdateTestBase):
assert bd_dict["month"] == self.month assert bd_dict["month"] == self.month
assert bd_dict["year"] == self.year assert bd_dict["year"] == self.year
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = {"day": self.day, "month": self.month, "year": self.year} json_dict = {"day": self.day, "month": self.month, "year": self.year}
bd = Birthdate.de_json(json_dict, bot) bd = Birthdate.de_json(json_dict, offline_bot)
assert isinstance(bd, Birthdate) assert isinstance(bd, Birthdate)
assert bd.day == self.day assert bd.day == self.day
assert bd.month == self.month assert bd.month == self.month

File diff suppressed because it is too large Load diff

View file

@ -37,15 +37,15 @@ class TestBotCommandWithoutRequest:
assert getattr(bot_command, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(bot_command, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(bot_command)) == len(set(mro_slots(bot_command))), "duplicate slot" assert len(mro_slots(bot_command)) == len(set(mro_slots(bot_command))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = {"command": self.command, "description": self.description} json_dict = {"command": self.command, "description": self.description}
bot_command = BotCommand.de_json(json_dict, bot) bot_command = BotCommand.de_json(json_dict, offline_bot)
assert bot_command.api_kwargs == {} assert bot_command.api_kwargs == {}
assert bot_command.command == self.command assert bot_command.command == self.command
assert bot_command.description == self.description assert bot_command.description == self.description
assert BotCommand.de_json(None, bot) is None assert BotCommand.de_json(None, offline_bot) is None
def test_to_dict(self, bot_command): def test_to_dict(self, bot_command):
bot_command_dict = bot_command.to_dict() bot_command_dict = bot_command.to_dict()

View file

@ -125,14 +125,14 @@ class TestBotCommandScopeWithoutRequest:
set(mro_slots(bot_command_scope)) set(mro_slots(bot_command_scope))
), "duplicate slot" ), "duplicate slot"
def test_de_json(self, bot, scope_class_and_type, chat_id): def test_de_json(self, offline_bot, scope_class_and_type, chat_id):
cls = scope_class_and_type[0] cls = scope_class_and_type[0]
type_ = scope_class_and_type[1] type_ = scope_class_and_type[1]
assert cls.de_json({}, bot) is None assert cls.de_json({}, offline_bot) is None
json_dict = {"type": type_, "chat_id": chat_id, "user_id": 42} json_dict = {"type": type_, "chat_id": chat_id, "user_id": 42}
bot_command_scope = BotCommandScope.de_json(json_dict, bot) bot_command_scope = BotCommandScope.de_json(json_dict, offline_bot)
assert set(bot_command_scope.api_kwargs.keys()) == {"chat_id", "user_id"} - set( assert set(bot_command_scope.api_kwargs.keys()) == {"chat_id", "user_id"} - set(
cls.__slots__ cls.__slots__
) )
@ -145,18 +145,18 @@ class TestBotCommandScopeWithoutRequest:
if "user_id" in cls.__slots__: if "user_id" in cls.__slots__:
assert bot_command_scope.user_id == 42 assert bot_command_scope.user_id == 42
def test_de_json_invalid_type(self, bot): def test_de_json_invalid_type(self, offline_bot):
json_dict = {"type": "invalid", "chat_id": chat_id, "user_id": 42} json_dict = {"type": "invalid", "chat_id": chat_id, "user_id": 42}
bot_command_scope = BotCommandScope.de_json(json_dict, bot) bot_command_scope = BotCommandScope.de_json(json_dict, offline_bot)
assert type(bot_command_scope) is BotCommandScope assert type(bot_command_scope) is BotCommandScope
assert bot_command_scope.type == "invalid" assert bot_command_scope.type == "invalid"
def test_de_json_subclass(self, scope_class, bot, chat_id): def test_de_json_subclass(self, scope_class, offline_bot, chat_id):
"""This makes sure that e.g. BotCommandScopeDefault(data) never returns a """This makes sure that e.g. BotCommandScopeDefault(data) never returns a
BotCommandScopeChat instance.""" BotCommandScopeChat instance."""
json_dict = {"type": "invalid", "chat_id": chat_id, "user_id": 42} json_dict = {"type": "invalid", "chat_id": chat_id, "user_id": 42}
assert type(scope_class.de_json(json_dict, bot)) is scope_class assert type(scope_class.de_json(json_dict, offline_bot)) is scope_class
def test_to_dict(self, bot_command_scope): def test_to_dict(self, bot_command_scope):
bot_command_scope_dict = bot_command_scope.to_dict() bot_command_scope_dict = bot_command_scope.to_dict()
@ -172,7 +172,7 @@ class TestBotCommandScopeWithoutRequest:
assert type(BotCommandScope("default").type) is BotCommandScopeType assert type(BotCommandScope("default").type) is BotCommandScopeType
assert BotCommandScope("unknown").type == "unknown" assert BotCommandScope("unknown").type == "unknown"
def test_equality(self, bot_command_scope, bot): def test_equality(self, bot_command_scope, offline_bot):
a = BotCommandScope("base_type") a = BotCommandScope("base_type")
b = BotCommandScope("base_type") b = BotCommandScope("base_type")
c = bot_command_scope c = bot_command_scope
@ -200,7 +200,7 @@ class TestBotCommandScopeWithoutRequest:
if hasattr(c, "chat_id"): if hasattr(c, "chat_id"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["chat_id"] = 0 json_dict["chat_id"] = 0
f = c.__class__.de_json(json_dict, bot) f = c.__class__.de_json(json_dict, offline_bot)
assert c != f assert c != f
assert hash(c) != hash(f) assert hash(c) != hash(f)
@ -208,7 +208,7 @@ class TestBotCommandScopeWithoutRequest:
if hasattr(c, "user_id"): if hasattr(c, "user_id"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["user_id"] = 0 json_dict["user_id"] = 0
g = c.__class__.de_json(json_dict, bot) g = c.__class__.de_json(json_dict, offline_bot)
assert c != g assert c != g
assert hash(c) != hash(g) assert hash(c) != hash(g)

View file

@ -139,7 +139,7 @@ class TestBusinessConnectionWithoutRequest(BusinessTestBase):
assert bc.api_kwargs == {} assert bc.api_kwargs == {}
assert isinstance(bc, BusinessConnection) assert isinstance(bc, BusinessConnection)
def test_de_json_localization(self, bot, raw_bot, tz_bot): def test_de_json_localization(self, offline_bot, raw_bot, tz_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"user": self.user.to_dict(), "user": self.user.to_dict(),
@ -148,7 +148,7 @@ class TestBusinessConnectionWithoutRequest(BusinessTestBase):
"can_reply": self.can_reply, "can_reply": self.can_reply,
"is_enabled": self.is_enabled, "is_enabled": self.is_enabled,
} }
chat_bot = BusinessConnection.de_json(json_dict, bot) chat_bot = BusinessConnection.de_json(json_dict, offline_bot)
chat_bot_raw = BusinessConnection.de_json(json_dict, raw_bot) chat_bot_raw = BusinessConnection.de_json(json_dict, raw_bot)
chat_bot_tz = BusinessConnection.de_json(json_dict, tz_bot) chat_bot_tz = BusinessConnection.de_json(json_dict, tz_bot)

View file

@ -94,7 +94,7 @@ class TestCallbackQueryWithoutRequest(CallbackQueryTestBase):
assert getattr(callback_query, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(callback_query, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(callback_query)) == len(set(mro_slots(callback_query))), "same slot" assert len(mro_slots(callback_query)) == len(set(mro_slots(callback_query))), "same slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"from": self.from_user.to_dict(), "from": self.from_user.to_dict(),
@ -104,7 +104,7 @@ class TestCallbackQueryWithoutRequest(CallbackQueryTestBase):
"inline_message_id": self.inline_message_id, "inline_message_id": self.inline_message_id,
"game_short_name": self.game_short_name, "game_short_name": self.game_short_name,
} }
callback_query = CallbackQuery.de_json(json_dict, bot) callback_query = CallbackQuery.de_json(json_dict, offline_bot)
assert callback_query.api_kwargs == {} assert callback_query.api_kwargs == {}
assert callback_query.id == self.id_ assert callback_query.id == self.id_

View file

@ -63,7 +63,7 @@ class TestChatWithoutRequest(ChatTestBase):
assert getattr(chat, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(chat, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(chat)) == len(set(mro_slots(chat))), "duplicate slot" assert len(mro_slots(chat)) == len(set(mro_slots(chat))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"title": self.title, "title": self.title,
@ -73,7 +73,7 @@ class TestChatWithoutRequest(ChatTestBase):
"first_name": self.first_name, "first_name": self.first_name,
"last_name": self.last_name, "last_name": self.last_name,
} }
chat = Chat.de_json(json_dict, bot) chat = Chat.de_json(json_dict, offline_bot)
assert chat.id == self.id_ assert chat.id == self.id_
assert chat.title == self.title assert chat.title == self.title

View file

@ -50,7 +50,7 @@ class TestChatAdministratorRightsWithoutRequest:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, chat_admin_rights): def test_de_json(self, offline_bot, chat_admin_rights):
json_dict = { json_dict = {
"can_change_info": True, "can_change_info": True,
"can_delete_messages": True, "can_delete_messages": True,
@ -68,7 +68,7 @@ class TestChatAdministratorRightsWithoutRequest:
"can_edit_stories": True, "can_edit_stories": True,
"can_delete_stories": True, "can_delete_stories": True,
} }
chat_administrator_rights_de = ChatAdministratorRights.de_json(json_dict, bot) chat_administrator_rights_de = ChatAdministratorRights.de_json(json_dict, offline_bot)
assert chat_administrator_rights_de.api_kwargs == {} assert chat_administrator_rights_de.api_kwargs == {}
assert chat_admin_rights == chat_administrator_rights_de assert chat_admin_rights == chat_administrator_rights_de

View file

@ -168,12 +168,12 @@ class TestBackgroundTypeWithoutRequest:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json_required_args(self, bot, background_type): def test_de_json_required_args(self, offline_bot, background_type):
cls = background_type.__class__ cls = background_type.__class__
assert cls.de_json({}, bot) is None assert cls.de_json({}, offline_bot) is None
json_dict = make_json_dict(background_type) json_dict = make_json_dict(background_type)
const_background_type = BackgroundType.de_json(json_dict, bot) const_background_type = BackgroundType.de_json(json_dict, offline_bot)
assert const_background_type.api_kwargs == {} assert const_background_type.api_kwargs == {}
assert isinstance(const_background_type, BackgroundType) assert isinstance(const_background_type, BackgroundType)
@ -181,9 +181,9 @@ class TestBackgroundTypeWithoutRequest:
for bg_type_at, const_bg_type_at in iter_args(background_type, const_background_type): for bg_type_at, const_bg_type_at in iter_args(background_type, const_background_type):
assert bg_type_at == const_bg_type_at assert bg_type_at == const_bg_type_at
def test_de_json_all_args(self, bot, background_type): def test_de_json_all_args(self, offline_bot, background_type):
json_dict = make_json_dict(background_type, include_optional_args=True) json_dict = make_json_dict(background_type, include_optional_args=True)
const_background_type = BackgroundType.de_json(json_dict, bot) const_background_type = BackgroundType.de_json(json_dict, offline_bot)
assert const_background_type.api_kwargs == {} assert const_background_type.api_kwargs == {}
@ -194,19 +194,19 @@ class TestBackgroundTypeWithoutRequest:
): ):
assert bg_type_at == const_bg_type_at assert bg_type_at == const_bg_type_at
def test_de_json_invalid_type(self, background_type, bot): def test_de_json_invalid_type(self, background_type, offline_bot):
json_dict = {"type": "invalid", "theme_name": BTDefaults.theme_name} json_dict = {"type": "invalid", "theme_name": BTDefaults.theme_name}
background_type = BackgroundType.de_json(json_dict, bot) background_type = BackgroundType.de_json(json_dict, offline_bot)
assert type(background_type) is BackgroundType assert type(background_type) is BackgroundType
assert background_type.type == "invalid" assert background_type.type == "invalid"
def test_de_json_subclass(self, background_type, bot, chat_id): def test_de_json_subclass(self, background_type, offline_bot, chat_id):
"""This makes sure that e.g. BackgroundTypeFill(data, bot) never returns a """This makes sure that e.g. BackgroundTypeFill(data, offline_bot) never returns a
BackgroundTypeWallpaper instance.""" BackgroundTypeWallpaper instance."""
cls = background_type.__class__ cls = background_type.__class__
json_dict = make_json_dict(background_type, True) json_dict = make_json_dict(background_type, True)
assert type(cls.de_json(json_dict, bot)) is cls assert type(cls.de_json(json_dict, offline_bot)) is cls
def test_to_dict(self, background_type): def test_to_dict(self, background_type):
bg_type_dict = background_type.to_dict() bg_type_dict = background_type.to_dict()
@ -275,12 +275,12 @@ class TestBackgroundFillWithoutRequest:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json_required_args(self, bot, background_fill): def test_de_json_required_args(self, offline_bot, background_fill):
cls = background_fill.__class__ cls = background_fill.__class__
assert cls.de_json({}, bot) is None assert cls.de_json({}, offline_bot) is None
json_dict = make_json_dict(background_fill) json_dict = make_json_dict(background_fill)
const_background_fill = BackgroundFill.de_json(json_dict, bot) const_background_fill = BackgroundFill.de_json(json_dict, offline_bot)
assert const_background_fill.api_kwargs == {} assert const_background_fill.api_kwargs == {}
assert isinstance(const_background_fill, BackgroundFill) assert isinstance(const_background_fill, BackgroundFill)
@ -288,9 +288,9 @@ class TestBackgroundFillWithoutRequest:
for bg_fill_at, const_bg_fill_at in iter_args(background_fill, const_background_fill): for bg_fill_at, const_bg_fill_at in iter_args(background_fill, const_background_fill):
assert bg_fill_at == const_bg_fill_at assert bg_fill_at == const_bg_fill_at
def test_de_json_all_args(self, bot, background_fill): def test_de_json_all_args(self, offline_bot, background_fill):
json_dict = make_json_dict(background_fill, include_optional_args=True) json_dict = make_json_dict(background_fill, include_optional_args=True)
const_background_fill = BackgroundFill.de_json(json_dict, bot) const_background_fill = BackgroundFill.de_json(json_dict, offline_bot)
assert const_background_fill.api_kwargs == {} assert const_background_fill.api_kwargs == {}
@ -301,19 +301,19 @@ class TestBackgroundFillWithoutRequest:
): ):
assert bg_fill_at == const_bg_fill_at assert bg_fill_at == const_bg_fill_at
def test_de_json_invalid_type(self, background_fill, bot): def test_de_json_invalid_type(self, background_fill, offline_bot):
json_dict = {"type": "invalid", "theme_name": BTDefaults.theme_name} json_dict = {"type": "invalid", "theme_name": BTDefaults.theme_name}
background_fill = BackgroundFill.de_json(json_dict, bot) background_fill = BackgroundFill.de_json(json_dict, offline_bot)
assert type(background_fill) is BackgroundFill assert type(background_fill) is BackgroundFill
assert background_fill.type == "invalid" assert background_fill.type == "invalid"
def test_de_json_subclass(self, background_fill, bot): def test_de_json_subclass(self, background_fill, offline_bot):
"""This makes sure that e.g. BackgroundFillSolid(data, bot) never returns a """This makes sure that e.g. BackgroundFillSolid(data, offline_bot) never returns a
BackgroundFillGradient instance.""" BackgroundFillGradient instance."""
cls = background_fill.__class__ cls = background_fill.__class__
json_dict = make_json_dict(background_fill, True) json_dict = make_json_dict(background_fill, True)
assert type(cls.de_json(json_dict, bot)) is cls assert type(cls.de_json(json_dict, offline_bot)) is cls
def test_to_dict(self, background_fill): def test_to_dict(self, background_fill):
bg_fill_dict = background_fill.to_dict() bg_fill_dict = background_fill.to_dict()

View file

@ -170,13 +170,13 @@ class TestChatBoostSourceTypesWithoutRequest:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json_required_args(self, bot, chat_boost_source): def test_de_json_required_args(self, offline_bot, chat_boost_source):
cls = chat_boost_source.__class__ cls = chat_boost_source.__class__
assert cls.de_json({}, bot) is None assert cls.de_json({}, offline_bot) is None
assert ChatBoost.de_json({}, bot) is None assert ChatBoost.de_json({}, offline_bot) is None
json_dict = make_json_dict(chat_boost_source) json_dict = make_json_dict(chat_boost_source)
const_boost_source = ChatBoostSource.de_json(json_dict, bot) const_boost_source = ChatBoostSource.de_json(json_dict, offline_bot)
assert const_boost_source.api_kwargs == {} assert const_boost_source.api_kwargs == {}
assert isinstance(const_boost_source, ChatBoostSource) assert isinstance(const_boost_source, ChatBoostSource)
@ -186,9 +186,9 @@ class TestChatBoostSourceTypesWithoutRequest:
): ):
assert chat_mem_type_at == const_chat_mem_at assert chat_mem_type_at == const_chat_mem_at
def test_de_json_all_args(self, bot, chat_boost_source): def test_de_json_all_args(self, offline_bot, chat_boost_source):
json_dict = make_json_dict(chat_boost_source, include_optional_args=True) json_dict = make_json_dict(chat_boost_source, include_optional_args=True)
const_boost_source = ChatBoostSource.de_json(json_dict, bot) const_boost_source = ChatBoostSource.de_json(json_dict, offline_bot)
assert const_boost_source.api_kwargs == {} assert const_boost_source.api_kwargs == {}
assert isinstance(const_boost_source, ChatBoostSource) assert isinstance(const_boost_source, ChatBoostSource)
@ -198,19 +198,19 @@ class TestChatBoostSourceTypesWithoutRequest:
): ):
assert c_mem_type_at == const_c_mem_at assert c_mem_type_at == const_c_mem_at
def test_de_json_invalid_source(self, chat_boost_source, bot): def test_de_json_invalid_source(self, chat_boost_source, offline_bot):
json_dict = {"source": "invalid"} json_dict = {"source": "invalid"}
chat_boost_source = ChatBoostSource.de_json(json_dict, bot) chat_boost_source = ChatBoostSource.de_json(json_dict, offline_bot)
assert type(chat_boost_source) is ChatBoostSource assert type(chat_boost_source) is ChatBoostSource
assert chat_boost_source.source == "invalid" assert chat_boost_source.source == "invalid"
def test_de_json_subclass(self, chat_boost_source, bot): def test_de_json_subclass(self, chat_boost_source, offline_bot):
"""This makes sure that e.g. ChatBoostSourcePremium(data, bot) never returns a """This makes sure that e.g. ChatBoostSourcePremium(data, offline_bot) never returns a
ChatBoostSourceGiftCode instance.""" ChatBoostSourceGiftCode instance."""
cls = chat_boost_source.__class__ cls = chat_boost_source.__class__
json_dict = make_json_dict(chat_boost_source, True) json_dict = make_json_dict(chat_boost_source, True)
assert type(cls.de_json(json_dict, bot)) is cls assert type(cls.de_json(json_dict, offline_bot)) is cls
def test_to_dict(self, chat_boost_source): def test_to_dict(self, chat_boost_source):
chat_boost_dict = chat_boost_source.to_dict() chat_boost_dict = chat_boost_source.to_dict()
@ -263,14 +263,14 @@ class TestChatBoostWithoutRequest(ChatBoostDefaults):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, chat_boost): def test_de_json(self, offline_bot, chat_boost):
json_dict = { json_dict = {
"boost_id": "2", "boost_id": "2",
"add_date": self.date, "add_date": self.date,
"expiration_date": self.date, "expiration_date": self.date,
"source": self.default_source.to_dict(), "source": self.default_source.to_dict(),
} }
cb = ChatBoost.de_json(json_dict, bot) cb = ChatBoost.de_json(json_dict, offline_bot)
assert isinstance(cb, ChatBoost) assert isinstance(cb, ChatBoost)
assert isinstance(cb.add_date, datetime.datetime) assert isinstance(cb.add_date, datetime.datetime)
@ -284,7 +284,7 @@ class TestChatBoostWithoutRequest(ChatBoostDefaults):
for slot in cb.__slots__: for slot in cb.__slots__:
assert getattr(cb, slot) == getattr(chat_boost, slot), f"attribute {slot} differs" assert getattr(cb, slot) == getattr(chat_boost, slot), f"attribute {slot} differs"
def test_de_json_localization(self, bot, raw_bot, tz_bot): def test_de_json_localization(self, offline_bot, raw_bot, tz_bot):
json_dict = { json_dict = {
"boost_id": "2", "boost_id": "2",
"add_date": self.date, "add_date": self.date,
@ -292,7 +292,7 @@ class TestChatBoostWithoutRequest(ChatBoostDefaults):
"source": self.default_source.to_dict(), "source": self.default_source.to_dict(),
} }
cb_bot = ChatBoost.de_json(json_dict, bot) cb_bot = ChatBoost.de_json(json_dict, offline_bot)
cb_raw = ChatBoost.de_json(json_dict, raw_bot) cb_raw = ChatBoost.de_json(json_dict, raw_bot)
cb_tz = ChatBoost.de_json(json_dict, tz_bot) cb_tz = ChatBoost.de_json(json_dict, tz_bot)
@ -347,7 +347,7 @@ class TestChatBoostUpdatedWithoutRequest(ChatBoostDefaults):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, chat_boost): def test_de_json(self, offline_bot, chat_boost):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"boost": { "boost": {
@ -357,7 +357,7 @@ class TestChatBoostUpdatedWithoutRequest(ChatBoostDefaults):
"source": self.default_source.to_dict(), "source": self.default_source.to_dict(),
}, },
} }
cbu = ChatBoostUpdated.de_json(json_dict, bot) cbu = ChatBoostUpdated.de_json(json_dict, offline_bot)
assert isinstance(cbu, ChatBoostUpdated) assert isinstance(cbu, ChatBoostUpdated)
assert cbu.chat == self.chat assert cbu.chat == self.chat
@ -420,14 +420,14 @@ class TestChatBoostRemovedWithoutRequest(ChatBoostDefaults):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, chat_boost_removed): def test_de_json(self, offline_bot, chat_boost_removed):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"boost_id": "2", "boost_id": "2",
"remove_date": self.date, "remove_date": self.date,
"source": self.default_source.to_dict(), "source": self.default_source.to_dict(),
} }
cbr = ChatBoostRemoved.de_json(json_dict, bot) cbr = ChatBoostRemoved.de_json(json_dict, offline_bot)
assert isinstance(cbr, ChatBoostRemoved) assert isinstance(cbr, ChatBoostRemoved)
assert cbr.chat == self.chat assert cbr.chat == self.chat
@ -435,7 +435,7 @@ class TestChatBoostRemovedWithoutRequest(ChatBoostDefaults):
assert to_timestamp(cbr.remove_date) == self.date assert to_timestamp(cbr.remove_date) == self.date
assert cbr.source == self.default_source assert cbr.source == self.default_source
def test_de_json_localization(self, bot, raw_bot, tz_bot): def test_de_json_localization(self, offline_bot, raw_bot, tz_bot):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"boost_id": "2", "boost_id": "2",
@ -443,7 +443,7 @@ class TestChatBoostRemovedWithoutRequest(ChatBoostDefaults):
"source": self.default_source.to_dict(), "source": self.default_source.to_dict(),
} }
cbr_bot = ChatBoostRemoved.de_json(json_dict, bot) cbr_bot = ChatBoostRemoved.de_json(json_dict, offline_bot)
cbr_raw = ChatBoostRemoved.de_json(json_dict, raw_bot) cbr_raw = ChatBoostRemoved.de_json(json_dict, raw_bot)
cbr_tz = ChatBoostRemoved.de_json(json_dict, tz_bot) cbr_tz = ChatBoostRemoved.de_json(json_dict, tz_bot)
@ -498,7 +498,7 @@ class TestUserChatBoostsWithoutRequest(ChatBoostDefaults):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, user_chat_boosts): def test_de_json(self, offline_bot, user_chat_boosts):
json_dict = { json_dict = {
"boosts": [ "boosts": [
{ {
@ -509,7 +509,7 @@ class TestUserChatBoostsWithoutRequest(ChatBoostDefaults):
} }
] ]
} }
ucb = UserChatBoosts.de_json(json_dict, bot) ucb = UserChatBoosts.de_json(json_dict, offline_bot)
assert isinstance(ucb, UserChatBoosts) assert isinstance(ucb, UserChatBoosts)
assert isinstance(ucb.boosts[0], ChatBoost) assert isinstance(ucb.boosts[0], ChatBoost)
@ -525,7 +525,7 @@ class TestUserChatBoostsWithoutRequest(ChatBoostDefaults):
assert isinstance(user_chat_boosts_dict["boosts"], list) assert isinstance(user_chat_boosts_dict["boosts"], list)
assert user_chat_boosts_dict["boosts"][0] == user_chat_boosts.boosts[0].to_dict() assert user_chat_boosts_dict["boosts"][0] == user_chat_boosts.boosts[0].to_dict()
async def test_get_user_chat_boosts(self, monkeypatch, bot): async def test_get_user_chat_boosts(self, monkeypatch, offline_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters data = request_data.json_parameters
chat_id = data["chat_id"] == "3" chat_id = data["chat_id"] == "3"
@ -534,9 +534,9 @@ class TestUserChatBoostsWithoutRequest(ChatBoostDefaults):
pytest.fail("I got wrong parameters in post") pytest.fail("I got wrong parameters in post")
return data return data
monkeypatch.setattr(bot.request, "post", make_assertion) monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await bot.get_user_chat_boosts("3", 2) assert await offline_bot.get_user_chat_boosts("3", 2)
class TestUserChatBoostsWithRequest(ChatBoostDefaults): class TestUserChatBoostsWithRequest(ChatBoostDefaults):

View file

@ -150,7 +150,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase):
assert len(mro_slots(cfi)) == len(set(mro_slots(cfi))), "duplicate slot" assert len(mro_slots(cfi)) == len(set(mro_slots(cfi))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"title": self.title, "title": self.title,
@ -194,7 +194,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase):
"last_name": self.last_name, "last_name": self.last_name,
"can_send_paid_media": self.can_send_paid_media, "can_send_paid_media": self.can_send_paid_media,
} }
cfi = ChatFullInfo.de_json(json_dict, bot) cfi = ChatFullInfo.de_json(json_dict, offline_bot)
assert cfi.id == self.id_ assert cfi.id == self.id_
assert cfi.title == self.title assert cfi.title == self.title
assert cfi.type == self.type_ assert cfi.type == self.type_
@ -239,7 +239,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase):
assert cfi.max_reaction_count == self.max_reaction_count assert cfi.max_reaction_count == self.max_reaction_count
assert cfi.can_send_paid_media == self.can_send_paid_media assert cfi.can_send_paid_media == self.can_send_paid_media
def test_de_json_localization(self, bot, raw_bot, tz_bot): def test_de_json_localization(self, offline_bot, raw_bot, tz_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"type": self.type_, "type": self.type_,
@ -247,7 +247,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase):
"max_reaction_count": self.max_reaction_count, "max_reaction_count": self.max_reaction_count,
"emoji_status_expiration_date": to_timestamp(self.emoji_status_expiration_date), "emoji_status_expiration_date": to_timestamp(self.emoji_status_expiration_date),
} }
cfi_bot = ChatFullInfo.de_json(json_dict, bot) cfi_bot = ChatFullInfo.de_json(json_dict, offline_bot)
cfi_bot_raw = ChatFullInfo.de_json(json_dict, raw_bot) cfi_bot_raw = ChatFullInfo.de_json(json_dict, raw_bot)
cfi_bot_tz = ChatFullInfo.de_json(json_dict, tz_bot) cfi_bot_tz = ChatFullInfo.de_json(json_dict, tz_bot)

View file

@ -66,7 +66,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase):
assert getattr(invite_link, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(invite_link, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(invite_link)) == len(set(mro_slots(invite_link))), "duplicate slot" assert len(mro_slots(invite_link)) == len(set(mro_slots(invite_link))), "duplicate slot"
def test_de_json_required_args(self, bot, creator): def test_de_json_required_args(self, offline_bot, creator):
json_dict = { json_dict = {
"invite_link": self.link, "invite_link": self.link,
"creator": creator.to_dict(), "creator": creator.to_dict(),
@ -75,7 +75,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase):
"is_revoked": self.revoked, "is_revoked": self.revoked,
} }
invite_link = ChatInviteLink.de_json(json_dict, bot) invite_link = ChatInviteLink.de_json(json_dict, offline_bot)
assert invite_link.api_kwargs == {} assert invite_link.api_kwargs == {}
assert invite_link.invite_link == self.link assert invite_link.invite_link == self.link
@ -84,7 +84,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase):
assert invite_link.is_primary == self.primary assert invite_link.is_primary == self.primary
assert invite_link.is_revoked == self.revoked assert invite_link.is_revoked == self.revoked
def test_de_json_all_args(self, bot, creator): def test_de_json_all_args(self, offline_bot, creator):
json_dict = { json_dict = {
"invite_link": self.link, "invite_link": self.link,
"creator": creator.to_dict(), "creator": creator.to_dict(),
@ -99,7 +99,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase):
"subscription_price": self.subscription_price, "subscription_price": self.subscription_price,
} }
invite_link = ChatInviteLink.de_json(json_dict, bot) invite_link = ChatInviteLink.de_json(json_dict, offline_bot)
assert invite_link.api_kwargs == {} assert invite_link.api_kwargs == {}
assert invite_link.invite_link == self.link assert invite_link.invite_link == self.link
@ -115,7 +115,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase):
assert invite_link.subscription_period == self.subscription_period assert invite_link.subscription_period == self.subscription_period
assert invite_link.subscription_price == self.subscription_price assert invite_link.subscription_price == self.subscription_price
def test_de_json_localization(self, tz_bot, bot, raw_bot, creator): def test_de_json_localization(self, tz_bot, offline_bot, raw_bot, creator):
json_dict = { json_dict = {
"invite_link": self.link, "invite_link": self.link,
"creator": creator.to_dict(), "creator": creator.to_dict(),
@ -129,7 +129,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase):
} }
invite_link_raw = ChatInviteLink.de_json(json_dict, raw_bot) invite_link_raw = ChatInviteLink.de_json(json_dict, raw_bot)
invite_link_bot = ChatInviteLink.de_json(json_dict, bot) invite_link_bot = ChatInviteLink.de_json(json_dict, offline_bot)
invite_link_tz = ChatInviteLink.de_json(json_dict, tz_bot) invite_link_tz = ChatInviteLink.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable

View file

@ -70,14 +70,14 @@ class TestChatJoinRequestWithoutRequest(ChatJoinRequestTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, time): def test_de_json(self, offline_bot, time):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"from": self.from_user.to_dict(), "from": self.from_user.to_dict(),
"date": to_timestamp(time), "date": to_timestamp(time),
"user_chat_id": self.from_user.id, "user_chat_id": self.from_user.id,
} }
chat_join_request = ChatJoinRequest.de_json(json_dict, bot) chat_join_request = ChatJoinRequest.de_json(json_dict, offline_bot)
assert chat_join_request.api_kwargs == {} assert chat_join_request.api_kwargs == {}
assert chat_join_request.chat == self.chat assert chat_join_request.chat == self.chat
@ -87,7 +87,7 @@ class TestChatJoinRequestWithoutRequest(ChatJoinRequestTestBase):
assert chat_join_request.user_chat_id == self.from_user.id assert chat_join_request.user_chat_id == self.from_user.id
json_dict.update({"bio": self.bio, "invite_link": self.invite_link.to_dict()}) json_dict.update({"bio": self.bio, "invite_link": self.invite_link.to_dict()})
chat_join_request = ChatJoinRequest.de_json(json_dict, bot) chat_join_request = ChatJoinRequest.de_json(json_dict, offline_bot)
assert chat_join_request.api_kwargs == {} assert chat_join_request.api_kwargs == {}
assert chat_join_request.chat == self.chat assert chat_join_request.chat == self.chat
@ -98,7 +98,7 @@ class TestChatJoinRequestWithoutRequest(ChatJoinRequestTestBase):
assert chat_join_request.bio == self.bio assert chat_join_request.bio == self.bio
assert chat_join_request.invite_link == self.invite_link assert chat_join_request.invite_link == self.invite_link
def test_de_json_localization(self, tz_bot, bot, raw_bot, time): def test_de_json_localization(self, tz_bot, offline_bot, raw_bot, time):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"from": self.from_user.to_dict(), "from": self.from_user.to_dict(),
@ -107,7 +107,7 @@ class TestChatJoinRequestWithoutRequest(ChatJoinRequestTestBase):
} }
chatjoin_req_raw = ChatJoinRequest.de_json(json_dict, raw_bot) chatjoin_req_raw = ChatJoinRequest.de_json(json_dict, raw_bot)
chatjoin_req_bot = ChatJoinRequest.de_json(json_dict, bot) chatjoin_req_bot = ChatJoinRequest.de_json(json_dict, offline_bot)
chatjoin_req_tz = ChatJoinRequest.de_json(json_dict, tz_bot) chatjoin_req_tz = ChatJoinRequest.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable

View file

@ -40,12 +40,12 @@ class TestChatLocationWithoutRequest(ChatLocationTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"location": self.location.to_dict(), "location": self.location.to_dict(),
"address": self.address, "address": self.address,
} }
chat_location = ChatLocation.de_json(json_dict, bot) chat_location = ChatLocation.de_json(json_dict, offline_bot)
assert chat_location.api_kwargs == {} assert chat_location.api_kwargs == {}
assert chat_location.location == self.location assert chat_location.location == self.location

View file

@ -205,12 +205,12 @@ class TestChatMemberTypesWithoutRequest:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json_required_args(self, bot, chat_member_type): def test_de_json_required_args(self, offline_bot, chat_member_type):
cls = chat_member_type.__class__ cls = chat_member_type.__class__
assert cls.de_json({}, bot) is None assert cls.de_json({}, offline_bot) is None
json_dict = make_json_dict(chat_member_type) json_dict = make_json_dict(chat_member_type)
const_chat_member = ChatMember.de_json(json_dict, bot) const_chat_member = ChatMember.de_json(json_dict, offline_bot)
assert const_chat_member.api_kwargs == {} assert const_chat_member.api_kwargs == {}
assert isinstance(const_chat_member, ChatMember) assert isinstance(const_chat_member, ChatMember)
@ -218,9 +218,9 @@ class TestChatMemberTypesWithoutRequest:
for chat_mem_type_at, const_chat_mem_at in iter_args(chat_member_type, const_chat_member): for chat_mem_type_at, const_chat_mem_at in iter_args(chat_member_type, const_chat_member):
assert chat_mem_type_at == const_chat_mem_at assert chat_mem_type_at == const_chat_mem_at
def test_de_json_all_args(self, bot, chat_member_type): def test_de_json_all_args(self, offline_bot, chat_member_type):
json_dict = make_json_dict(chat_member_type, include_optional_args=True) json_dict = make_json_dict(chat_member_type, include_optional_args=True)
const_chat_member = ChatMember.de_json(json_dict, bot) const_chat_member = ChatMember.de_json(json_dict, offline_bot)
assert const_chat_member.api_kwargs == {} assert const_chat_member.api_kwargs == {}
assert isinstance(const_chat_member, ChatMember) assert isinstance(const_chat_member, ChatMember)
@ -228,14 +228,16 @@ class TestChatMemberTypesWithoutRequest:
for c_mem_type_at, const_c_mem_at in iter_args(chat_member_type, const_chat_member, True): for c_mem_type_at, const_c_mem_at in iter_args(chat_member_type, const_chat_member, True):
assert c_mem_type_at == const_c_mem_at assert c_mem_type_at == const_c_mem_at
def test_de_json_chatmemberbanned_localization(self, chat_member_type, tz_bot, bot, raw_bot): def test_de_json_chatmemberbanned_localization(
self, chat_member_type, tz_bot, offline_bot, raw_bot
):
# We only test two classes because the other three don't have datetimes in them. # We only test two classes because the other three don't have datetimes in them.
if isinstance( if isinstance(
chat_member_type, (ChatMemberBanned, ChatMemberRestricted, ChatMemberMember) chat_member_type, (ChatMemberBanned, ChatMemberRestricted, ChatMemberMember)
): ):
json_dict = make_json_dict(chat_member_type, include_optional_args=True) json_dict = make_json_dict(chat_member_type, include_optional_args=True)
chatmember_raw = ChatMember.de_json(json_dict, raw_bot) chatmember_raw = ChatMember.de_json(json_dict, raw_bot)
chatmember_bot = ChatMember.de_json(json_dict, bot) chatmember_bot = ChatMember.de_json(json_dict, offline_bot)
chatmember_tz = ChatMember.de_json(json_dict, tz_bot) chatmember_tz = ChatMember.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable
@ -248,19 +250,19 @@ class TestChatMemberTypesWithoutRequest:
assert chatmember_bot.until_date.tzinfo == UTC assert chatmember_bot.until_date.tzinfo == UTC
assert chatmember_offset == tz_bot_offset assert chatmember_offset == tz_bot_offset
def test_de_json_invalid_status(self, chat_member_type, bot): def test_de_json_invalid_status(self, chat_member_type, offline_bot):
json_dict = {"status": "invalid", "user": CMDefaults.user.to_dict()} json_dict = {"status": "invalid", "user": CMDefaults.user.to_dict()}
chat_member_type = ChatMember.de_json(json_dict, bot) chat_member_type = ChatMember.de_json(json_dict, offline_bot)
assert type(chat_member_type) is ChatMember assert type(chat_member_type) is ChatMember
assert chat_member_type.status == "invalid" assert chat_member_type.status == "invalid"
def test_de_json_subclass(self, chat_member_type, bot, chat_id): def test_de_json_subclass(self, chat_member_type, offline_bot, chat_id):
"""This makes sure that e.g. ChatMemberAdministrator(data, bot) never returns a """This makes sure that e.g. ChatMemberAdministrator(data, offline_bot) never returns a
ChatMemberBanned instance.""" ChatMemberBanned instance."""
cls = chat_member_type.__class__ cls = chat_member_type.__class__
json_dict = make_json_dict(chat_member_type, True) json_dict = make_json_dict(chat_member_type, True)
assert type(cls.de_json(json_dict, bot)) is cls assert type(cls.de_json(json_dict, offline_bot)) is cls
def test_to_dict(self, chat_member_type): def test_to_dict(self, chat_member_type):
chat_member_dict = chat_member_type.to_dict() chat_member_dict = chat_member_type.to_dict()

View file

@ -99,7 +99,9 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase):
assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(action)) == len(set(mro_slots(action))), "duplicate slot" assert len(mro_slots(action)) == len(set(mro_slots(action))), "duplicate slot"
def test_de_json_required_args(self, bot, user, chat, old_chat_member, new_chat_member, time): def test_de_json_required_args(
self, offline_bot, user, chat, old_chat_member, new_chat_member, time
):
json_dict = { json_dict = {
"chat": chat.to_dict(), "chat": chat.to_dict(),
"from": user.to_dict(), "from": user.to_dict(),
@ -108,7 +110,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase):
"new_chat_member": new_chat_member.to_dict(), "new_chat_member": new_chat_member.to_dict(),
} }
chat_member_updated = ChatMemberUpdated.de_json(json_dict, bot) chat_member_updated = ChatMemberUpdated.de_json(json_dict, offline_bot)
assert chat_member_updated.api_kwargs == {} assert chat_member_updated.api_kwargs == {}
assert chat_member_updated.chat == chat assert chat_member_updated.chat == chat
@ -121,7 +123,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase):
assert chat_member_updated.via_chat_folder_invite_link is None assert chat_member_updated.via_chat_folder_invite_link is None
def test_de_json_all_args( def test_de_json_all_args(
self, bot, user, time, invite_link, chat, old_chat_member, new_chat_member self, offline_bot, user, time, invite_link, chat, old_chat_member, new_chat_member
): ):
json_dict = { json_dict = {
"chat": chat.to_dict(), "chat": chat.to_dict(),
@ -134,7 +136,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase):
"via_join_request": True, "via_join_request": True,
} }
chat_member_updated = ChatMemberUpdated.de_json(json_dict, bot) chat_member_updated = ChatMemberUpdated.de_json(json_dict, offline_bot)
assert chat_member_updated.api_kwargs == {} assert chat_member_updated.api_kwargs == {}
assert chat_member_updated.chat == chat assert chat_member_updated.chat == chat
@ -148,7 +150,16 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase):
assert chat_member_updated.via_join_request is True assert chat_member_updated.via_join_request is True
def test_de_json_localization( def test_de_json_localization(
self, bot, raw_bot, tz_bot, user, chat, old_chat_member, new_chat_member, time, invite_link self,
offline_bot,
raw_bot,
tz_bot,
user,
chat,
old_chat_member,
new_chat_member,
time,
invite_link,
): ):
json_dict = { json_dict = {
"chat": chat.to_dict(), "chat": chat.to_dict(),
@ -159,7 +170,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase):
"invite_link": invite_link.to_dict(), "invite_link": invite_link.to_dict(),
} }
chat_member_updated_bot = ChatMemberUpdated.de_json(json_dict, bot) chat_member_updated_bot = ChatMemberUpdated.de_json(json_dict, offline_bot)
chat_member_updated_raw = ChatMemberUpdated.de_json(json_dict, raw_bot) chat_member_updated_raw = ChatMemberUpdated.de_json(json_dict, raw_bot)
chat_member_updated_tz = ChatMemberUpdated.de_json(json_dict, tz_bot) chat_member_updated_tz = ChatMemberUpdated.de_json(json_dict, tz_bot)

View file

@ -67,7 +67,7 @@ class TestChatPermissionsWithoutRequest(ChatPermissionsTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"can_send_messages": self.can_send_messages, "can_send_messages": self.can_send_messages,
"can_send_media_messages": "can_send_media_messages", "can_send_media_messages": "can_send_media_messages",
@ -84,7 +84,7 @@ class TestChatPermissionsWithoutRequest(ChatPermissionsTestBase):
"can_send_video_notes": self.can_send_video_notes, "can_send_video_notes": self.can_send_video_notes,
"can_send_voice_notes": self.can_send_voice_notes, "can_send_voice_notes": self.can_send_voice_notes,
} }
permissions = ChatPermissions.de_json(json_dict, bot) permissions = ChatPermissions.de_json(json_dict, offline_bot)
assert permissions.api_kwargs == {"can_send_media_messages": "can_send_media_messages"} assert permissions.api_kwargs == {"can_send_media_messages": "can_send_media_messages"}
assert permissions.can_send_messages == self.can_send_messages assert permissions.can_send_messages == self.can_send_messages

View file

@ -49,16 +49,16 @@ class TestChosenInlineResultWithoutRequest(ChosenInlineResultTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json_required(self, bot, user): def test_de_json_required(self, offline_bot, user):
json_dict = {"result_id": self.result_id, "from": user.to_dict(), "query": self.query} json_dict = {"result_id": self.result_id, "from": user.to_dict(), "query": self.query}
result = ChosenInlineResult.de_json(json_dict, bot) result = ChosenInlineResult.de_json(json_dict, offline_bot)
assert result.api_kwargs == {} assert result.api_kwargs == {}
assert result.result_id == self.result_id assert result.result_id == self.result_id
assert result.from_user == user assert result.from_user == user
assert result.query == self.query assert result.query == self.query
def test_de_json_all(self, bot, user): def test_de_json_all(self, offline_bot, user):
loc = Location(-42.003, 34.004) loc = Location(-42.003, 34.004)
json_dict = { json_dict = {
"result_id": self.result_id, "result_id": self.result_id,
@ -67,7 +67,7 @@ class TestChosenInlineResultWithoutRequest(ChosenInlineResultTestBase):
"location": loc.to_dict(), "location": loc.to_dict(),
"inline_message_id": "a random id", "inline_message_id": "a random id",
} }
result = ChosenInlineResult.de_json(json_dict, bot) result = ChosenInlineResult.de_json(json_dict, offline_bot)
assert result.api_kwargs == {} assert result.api_kwargs == {}
assert result.result_id == self.result_id assert result.result_id == self.result_id

View file

@ -39,14 +39,14 @@ class TestDiceWithoutRequest(DiceTestBase):
assert len(mro_slots(dice)) == len(set(mro_slots(dice))), "duplicate slot" assert len(mro_slots(dice)) == len(set(mro_slots(dice))), "duplicate slot"
@pytest.mark.parametrize("emoji", Dice.ALL_EMOJI) @pytest.mark.parametrize("emoji", Dice.ALL_EMOJI)
def test_de_json(self, bot, emoji): def test_de_json(self, offline_bot, emoji):
json_dict = {"value": self.value, "emoji": emoji} json_dict = {"value": self.value, "emoji": emoji}
dice = Dice.de_json(json_dict, bot) dice = Dice.de_json(json_dict, offline_bot)
assert dice.api_kwargs == {} assert dice.api_kwargs == {}
assert dice.value == self.value assert dice.value == self.value
assert dice.emoji == emoji assert dice.emoji == emoji
assert Dice.de_json(None, bot) is None assert Dice.de_json(None, offline_bot) is None
def test_to_dict(self, dice): def test_to_dict(self, dice):
dice_dict = dice.to_dict() dice_dict = dice.to_dict()

View file

@ -86,8 +86,8 @@ class TestForumTopicWithoutRequest:
assert forum_topic_object.name == TEST_TOPIC_NAME assert forum_topic_object.name == TEST_TOPIC_NAME
assert forum_topic_object.icon_custom_emoji_id == emoji_id assert forum_topic_object.icon_custom_emoji_id == emoji_id
def test_de_json(self, bot, emoji_id, forum_group_id): def test_de_json(self, offline_bot, emoji_id, forum_group_id):
assert ForumTopic.de_json(None, bot=bot) is None assert ForumTopic.de_json(None, bot=offline_bot) is None
json_dict = { json_dict = {
"message_thread_id": forum_group_id, "message_thread_id": forum_group_id,
@ -95,7 +95,7 @@ class TestForumTopicWithoutRequest:
"icon_color": TEST_TOPIC_ICON_COLOR, "icon_color": TEST_TOPIC_ICON_COLOR,
"icon_custom_emoji_id": emoji_id, "icon_custom_emoji_id": emoji_id,
} }
topic = ForumTopic.de_json(json_dict, bot) topic = ForumTopic.de_json(json_dict, offline_bot)
assert topic.api_kwargs == {} assert topic.api_kwargs == {}
assert topic.message_thread_id == forum_group_id assert topic.message_thread_id == forum_group_id
@ -333,11 +333,11 @@ class TestForumTopicCreatedWithoutRequest:
assert topic_created.icon_color == TEST_TOPIC_ICON_COLOR assert topic_created.icon_color == TEST_TOPIC_ICON_COLOR
assert topic_created.name == TEST_TOPIC_NAME assert topic_created.name == TEST_TOPIC_NAME
def test_de_json(self, bot): def test_de_json(self, offline_bot):
assert ForumTopicCreated.de_json(None, bot=bot) is None assert ForumTopicCreated.de_json(None, bot=offline_bot) is None
json_dict = {"icon_color": TEST_TOPIC_ICON_COLOR, "name": TEST_TOPIC_NAME} json_dict = {"icon_color": TEST_TOPIC_ICON_COLOR, "name": TEST_TOPIC_NAME}
action = ForumTopicCreated.de_json(json_dict, bot) action = ForumTopicCreated.de_json(json_dict, offline_bot)
assert action.api_kwargs == {} assert action.api_kwargs == {}
assert action.icon_color == TEST_TOPIC_ICON_COLOR assert action.icon_color == TEST_TOPIC_ICON_COLOR

View file

@ -66,7 +66,7 @@ class TestGiveawayWithoutRequest:
assert getattr(giveaway, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(giveaway, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(giveaway)) == len(set(mro_slots(giveaway))), "duplicate slot" assert len(mro_slots(giveaway)) == len(set(mro_slots(giveaway))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"chats": [chat.to_dict() for chat in self.chats], "chats": [chat.to_dict() for chat in self.chats],
"winners_selection_date": to_timestamp(self.winners_selection_date), "winners_selection_date": to_timestamp(self.winners_selection_date),
@ -78,7 +78,7 @@ class TestGiveawayWithoutRequest:
"premium_subscription_month_count": self.premium_subscription_month_count, "premium_subscription_month_count": self.premium_subscription_month_count,
} }
giveaway = Giveaway.de_json(json_dict, bot) giveaway = Giveaway.de_json(json_dict, offline_bot)
assert giveaway.api_kwargs == {} assert giveaway.api_kwargs == {}
assert giveaway.chats == tuple(self.chats) assert giveaway.chats == tuple(self.chats)
@ -90,9 +90,9 @@ class TestGiveawayWithoutRequest:
assert giveaway.country_codes == tuple(self.country_codes) assert giveaway.country_codes == tuple(self.country_codes)
assert giveaway.premium_subscription_month_count == self.premium_subscription_month_count assert giveaway.premium_subscription_month_count == self.premium_subscription_month_count
assert Giveaway.de_json(None, bot) is None assert Giveaway.de_json(None, offline_bot) is None
def test_de_json_localization(self, tz_bot, bot, raw_bot): def test_de_json_localization(self, tz_bot, offline_bot, raw_bot):
json_dict = { json_dict = {
"chats": [chat.to_dict() for chat in self.chats], "chats": [chat.to_dict() for chat in self.chats],
"winners_selection_date": to_timestamp(self.winners_selection_date), "winners_selection_date": to_timestamp(self.winners_selection_date),
@ -105,7 +105,7 @@ class TestGiveawayWithoutRequest:
} }
giveaway_raw = Giveaway.de_json(json_dict, raw_bot) giveaway_raw = Giveaway.de_json(json_dict, raw_bot)
giveaway_bot = Giveaway.de_json(json_dict, bot) giveaway_bot = Giveaway.de_json(json_dict, offline_bot)
giveaway_bot_tz = Giveaway.de_json(json_dict, tz_bot) giveaway_bot_tz = Giveaway.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable
@ -213,7 +213,7 @@ class TestGiveawayWinnersWithoutRequest:
set(mro_slots(giveaway_winners)) set(mro_slots(giveaway_winners))
), "duplicate slot" ), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"giveaway_message_id": self.giveaway_message_id, "giveaway_message_id": self.giveaway_message_id,
@ -228,7 +228,7 @@ class TestGiveawayWinnersWithoutRequest:
"prize_description": self.prize_description, "prize_description": self.prize_description,
} }
giveaway_winners = GiveawayWinners.de_json(json_dict, bot) giveaway_winners = GiveawayWinners.de_json(json_dict, offline_bot)
assert giveaway_winners.api_kwargs == {} assert giveaway_winners.api_kwargs == {}
assert giveaway_winners.chat == self.chat assert giveaway_winners.chat == self.chat
@ -246,9 +246,9 @@ class TestGiveawayWinnersWithoutRequest:
assert giveaway_winners.was_refunded == self.was_refunded assert giveaway_winners.was_refunded == self.was_refunded
assert giveaway_winners.prize_description == self.prize_description assert giveaway_winners.prize_description == self.prize_description
assert GiveawayWinners.de_json(None, bot) is None assert GiveawayWinners.de_json(None, offline_bot) is None
def test_de_json_localization(self, tz_bot, bot, raw_bot): def test_de_json_localization(self, tz_bot, offline_bot, raw_bot):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"giveaway_message_id": self.giveaway_message_id, "giveaway_message_id": self.giveaway_message_id,
@ -258,7 +258,7 @@ class TestGiveawayWinnersWithoutRequest:
} }
giveaway_winners_raw = GiveawayWinners.de_json(json_dict, raw_bot) giveaway_winners_raw = GiveawayWinners.de_json(json_dict, raw_bot)
giveaway_winners_bot = GiveawayWinners.de_json(json_dict, bot) giveaway_winners_bot = GiveawayWinners.de_json(json_dict, offline_bot)
giveaway_winners_bot_tz = GiveawayWinners.de_json(json_dict, tz_bot) giveaway_winners_bot_tz = GiveawayWinners.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable
@ -357,21 +357,21 @@ class TestGiveawayCompletedWithoutRequest:
set(mro_slots(giveaway_completed)) set(mro_slots(giveaway_completed))
), "duplicate slot" ), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"winner_count": self.winner_count, "winner_count": self.winner_count,
"unclaimed_prize_count": self.unclaimed_prize_count, "unclaimed_prize_count": self.unclaimed_prize_count,
"giveaway_message": self.giveaway_message.to_dict(), "giveaway_message": self.giveaway_message.to_dict(),
} }
giveaway_completed = GiveawayCompleted.de_json(json_dict, bot) giveaway_completed = GiveawayCompleted.de_json(json_dict, offline_bot)
assert giveaway_completed.api_kwargs == {} assert giveaway_completed.api_kwargs == {}
assert giveaway_completed.winner_count == self.winner_count assert giveaway_completed.winner_count == self.winner_count
assert giveaway_completed.unclaimed_prize_count == self.unclaimed_prize_count assert giveaway_completed.unclaimed_prize_count == self.unclaimed_prize_count
assert giveaway_completed.giveaway_message == self.giveaway_message assert giveaway_completed.giveaway_message == self.giveaway_message
assert GiveawayCompleted.de_json(None, bot) is None assert GiveawayCompleted.de_json(None, offline_bot) is None
def test_to_dict(self, giveaway_completed): def test_to_dict(self, giveaway_completed):
giveaway_completed_dict = giveaway_completed.to_dict() giveaway_completed_dict = giveaway_completed.to_dict()

View file

@ -51,16 +51,16 @@ class TestInlineQueryResultsButtonWithoutRequest(InlineQueryResultsButtonTestBas
assert inline_query_results_button_dict["start_parameter"] == self.start_parameter assert inline_query_results_button_dict["start_parameter"] == self.start_parameter
assert inline_query_results_button_dict["web_app"] == self.web_app.to_dict() assert inline_query_results_button_dict["web_app"] == self.web_app.to_dict()
def test_de_json(self, bot): def test_de_json(self, offline_bot):
assert InlineQueryResultsButton.de_json(None, bot) is None assert InlineQueryResultsButton.de_json(None, offline_bot) is None
assert InlineQueryResultsButton.de_json({}, bot) is None assert InlineQueryResultsButton.de_json({}, offline_bot) is None
json_dict = { json_dict = {
"text": self.text, "text": self.text,
"start_parameter": self.start_parameter, "start_parameter": self.start_parameter,
"web_app": self.web_app.to_dict(), "web_app": self.web_app.to_dict(),
} }
inline_query_results_button = InlineQueryResultsButton.de_json(json_dict, bot) inline_query_results_button = InlineQueryResultsButton.de_json(json_dict, offline_bot)
assert inline_query_results_button.text == self.text assert inline_query_results_button.text == self.text
assert inline_query_results_button.start_parameter == self.start_parameter assert inline_query_results_button.start_parameter == self.start_parameter

View file

@ -81,7 +81,7 @@ class TestKeyboardButtonWithoutRequest(KeyboardButtonTestBase):
assert keyboard_button_dict["request_users"] == keyboard_button.request_users.to_dict() assert keyboard_button_dict["request_users"] == keyboard_button.request_users.to_dict()
@pytest.mark.parametrize("request_user", [True, False]) @pytest.mark.parametrize("request_user", [True, False])
def test_de_json(self, bot, request_user): def test_de_json(self, request_user):
json_dict = { json_dict = {
"text": self.text, "text": self.text,
"request_location": self.request_location, "request_location": self.request_location,

View file

@ -57,14 +57,14 @@ class TestKeyboardButtonRequestUsersWithoutRequest(KeyboardButtonRequestUsersTes
assert request_users_dict["user_is_premium"] == self.user_is_premium assert request_users_dict["user_is_premium"] == self.user_is_premium
assert request_users_dict["max_quantity"] == self.max_quantity assert request_users_dict["max_quantity"] == self.max_quantity
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"request_id": self.request_id, "request_id": self.request_id,
"user_is_bot": self.user_is_bot, "user_is_bot": self.user_is_bot,
"user_is_premium": self.user_is_premium, "user_is_premium": self.user_is_premium,
"max_quantity": self.max_quantity, "max_quantity": self.max_quantity,
} }
request_users = KeyboardButtonRequestUsers.de_json(json_dict, bot) request_users = KeyboardButtonRequestUsers.de_json(json_dict, offline_bot)
assert request_users.api_kwargs == {} assert request_users.api_kwargs == {}
assert request_users.request_id == self.request_id assert request_users.request_id == self.request_id
@ -158,7 +158,7 @@ class TestKeyboardButtonRequestChatWithoutRequest(KeyboardButtonRequestChatTestB
) )
assert request_chat_dict["bot_is_member"] == self.bot_is_member assert request_chat_dict["bot_is_member"] == self.bot_is_member
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"request_id": self.request_id, "request_id": self.request_id,
"chat_is_channel": self.chat_is_channel, "chat_is_channel": self.chat_is_channel,
@ -168,7 +168,7 @@ class TestKeyboardButtonRequestChatWithoutRequest(KeyboardButtonRequestChatTestB
"bot_administrator_rights": self.bot_administrator_rights.to_dict(), "bot_administrator_rights": self.bot_administrator_rights.to_dict(),
"bot_is_member": self.bot_is_member, "bot_is_member": self.bot_is_member,
} }
request_chat = KeyboardButtonRequestChat.de_json(json_dict, bot) request_chat = KeyboardButtonRequestChat.de_json(json_dict, offline_bot)
assert request_chat.api_kwargs == {} assert request_chat.api_kwargs == {}
assert request_chat.request_id == self.request_id assert request_chat.request_id == self.request_id
@ -179,7 +179,7 @@ class TestKeyboardButtonRequestChatWithoutRequest(KeyboardButtonRequestChatTestB
assert request_chat.bot_administrator_rights == self.bot_administrator_rights assert request_chat.bot_administrator_rights == self.bot_administrator_rights
assert request_chat.bot_is_member == self.bot_is_member assert request_chat.bot_is_member == self.bot_is_member
empty_chat = KeyboardButtonRequestChat.de_json({}, bot) empty_chat = KeyboardButtonRequestChat.de_json({}, offline_bot)
assert empty_chat is None assert empty_chat is None
def test_equality(self): def test_equality(self):

View file

@ -59,20 +59,20 @@ class TestMaybeInaccessibleMessageWithoutRequest(MaybeInaccessibleMessageTestBas
assert maybe_inaccessible_message_dict["message_id"] == self.message_id assert maybe_inaccessible_message_dict["message_id"] == self.message_id
assert maybe_inaccessible_message_dict["date"] == to_timestamp(self.date) assert maybe_inaccessible_message_dict["date"] == to_timestamp(self.date)
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"message_id": self.message_id, "message_id": self.message_id,
"date": to_timestamp(self.date), "date": to_timestamp(self.date),
} }
maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, bot) maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, offline_bot)
assert maybe_inaccessible_message.api_kwargs == {} assert maybe_inaccessible_message.api_kwargs == {}
assert maybe_inaccessible_message.chat == self.chat assert maybe_inaccessible_message.chat == self.chat
assert maybe_inaccessible_message.message_id == self.message_id assert maybe_inaccessible_message.message_id == self.message_id
assert maybe_inaccessible_message.date == self.date assert maybe_inaccessible_message.date == self.date
def test_de_json_localization(self, tz_bot, bot, raw_bot): def test_de_json_localization(self, tz_bot, offline_bot, raw_bot):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"message_id": self.message_id, "message_id": self.message_id,
@ -80,7 +80,7 @@ class TestMaybeInaccessibleMessageWithoutRequest(MaybeInaccessibleMessageTestBas
} }
maybe_inaccessible_message_raw = MaybeInaccessibleMessage.de_json(json_dict, raw_bot) maybe_inaccessible_message_raw = MaybeInaccessibleMessage.de_json(json_dict, raw_bot)
maybe_inaccessible_message_bot = MaybeInaccessibleMessage.de_json(json_dict, bot) maybe_inaccessible_message_bot = MaybeInaccessibleMessage.de_json(json_dict, offline_bot)
maybe_inaccessible_message_bot_tz = MaybeInaccessibleMessage.de_json(json_dict, tz_bot) maybe_inaccessible_message_bot_tz = MaybeInaccessibleMessage.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable
@ -95,14 +95,14 @@ class TestMaybeInaccessibleMessageWithoutRequest(MaybeInaccessibleMessageTestBas
assert maybe_inaccessible_message_bot.date.tzinfo == UTC assert maybe_inaccessible_message_bot.date.tzinfo == UTC
assert maybe_inaccessible_message_bot_tz_offset == tz_bot_offset assert maybe_inaccessible_message_bot_tz_offset == tz_bot_offset
def test_de_json_zero_date(self, bot): def test_de_json_zero_date(self, offline_bot):
json_dict = { json_dict = {
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
"message_id": self.message_id, "message_id": self.message_id,
"date": 0, "date": 0,
} }
maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, bot) maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, offline_bot)
assert maybe_inaccessible_message.date == ZERO_DATE assert maybe_inaccessible_message.date == ZERO_DATE
assert maybe_inaccessible_message.date is ZERO_DATE assert maybe_inaccessible_message.date is ZERO_DATE

View file

@ -103,12 +103,12 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase):
assert getattr(menu_button, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(menu_button, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(menu_button)) == len(set(mro_slots(menu_button))), "duplicate slot" assert len(mro_slots(menu_button)) == len(set(mro_slots(menu_button))), "duplicate slot"
def test_de_json(self, bot, scope_class_and_type): def test_de_json(self, offline_bot, scope_class_and_type):
cls = scope_class_and_type[0] cls = scope_class_and_type[0]
type_ = scope_class_and_type[1] type_ = scope_class_and_type[1]
json_dict = {"type": type_, "text": self.text, "web_app": self.web_app.to_dict()} json_dict = {"type": type_, "text": self.text, "web_app": self.web_app.to_dict()}
menu_button = MenuButton.de_json(json_dict, bot) menu_button = MenuButton.de_json(json_dict, offline_bot)
assert set(menu_button.api_kwargs.keys()) == {"text", "web_app"} - set(cls.__slots__) assert set(menu_button.api_kwargs.keys()) == {"text", "web_app"} - set(cls.__slots__)
assert isinstance(menu_button, MenuButton) assert isinstance(menu_button, MenuButton)
@ -119,22 +119,22 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase):
if "text" in cls.__slots__: if "text" in cls.__slots__:
assert menu_button.text == self.text assert menu_button.text == self.text
assert cls.de_json(None, bot) is None assert cls.de_json(None, offline_bot) is None
assert MenuButton.de_json({}, bot) is None assert MenuButton.de_json({}, offline_bot) is None
def test_de_json_invalid_type(self, bot): def test_de_json_invalid_type(self, offline_bot):
json_dict = {"type": "invalid", "text": self.text, "web_app": self.web_app.to_dict()} json_dict = {"type": "invalid", "text": self.text, "web_app": self.web_app.to_dict()}
menu_button = MenuButton.de_json(json_dict, bot) menu_button = MenuButton.de_json(json_dict, offline_bot)
assert menu_button.api_kwargs == {"text": self.text, "web_app": self.web_app.to_dict()} assert menu_button.api_kwargs == {"text": self.text, "web_app": self.web_app.to_dict()}
assert type(menu_button) is MenuButton assert type(menu_button) is MenuButton
assert menu_button.type == "invalid" assert menu_button.type == "invalid"
def test_de_json_subclass(self, scope_class, bot): def test_de_json_subclass(self, scope_class, offline_bot):
"""This makes sure that e.g. MenuButtonDefault(data) never returns a """This makes sure that e.g. MenuButtonDefault(data) never returns a
MenuButtonChat instance.""" MenuButtonChat instance."""
json_dict = {"type": "invalid", "text": self.text, "web_app": self.web_app.to_dict()} json_dict = {"type": "invalid", "text": self.text, "web_app": self.web_app.to_dict()}
assert type(scope_class.de_json(json_dict, bot)) is scope_class assert type(scope_class.de_json(json_dict, offline_bot)) is scope_class
def test_de_json_empty_data(self, scope_class): def test_de_json_empty_data(self, scope_class):
if scope_class in (MenuButtonWebApp,): if scope_class in (MenuButtonWebApp,):
@ -157,7 +157,7 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase):
assert type(MenuButton("commands").type) is MenuButtonType assert type(MenuButton("commands").type) is MenuButtonType
assert MenuButton("unknown").type == "unknown" assert MenuButton("unknown").type == "unknown"
def test_equality(self, menu_button, bot): def test_equality(self, menu_button, offline_bot):
a = MenuButton("base_type") a = MenuButton("base_type")
b = MenuButton("base_type") b = MenuButton("base_type")
c = menu_button c = menu_button
@ -185,7 +185,7 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase):
if hasattr(c, "web_app"): if hasattr(c, "web_app"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["web_app"] = WebAppInfo("https://foo.bar/web_app").to_dict() json_dict["web_app"] = WebAppInfo("https://foo.bar/web_app").to_dict()
f = c.__class__.de_json(json_dict, bot) f = c.__class__.de_json(json_dict, offline_bot)
assert c != f assert c != f
assert hash(c) != hash(f) assert hash(c) != hash(f)
@ -193,7 +193,7 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase):
if hasattr(c, "text"): if hasattr(c, "text"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["text"] = "other text" json_dict["text"] = "other text"
g = c.__class__.de_json(json_dict, bot) g = c.__class__.de_json(json_dict, offline_bot)
assert c != g assert c != g
assert hash(c) != hash(g) assert hash(c) != hash(g)

View file

@ -568,8 +568,8 @@ class TestMessageWithoutRequest(MessageTestBase):
assert getattr(message, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(message, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(message)) == len(set(mro_slots(message))), "duplicate slot" assert len(mro_slots(message)) == len(set(mro_slots(message))), "duplicate slot"
def test_all_possibilities_de_json_and_to_dict(self, bot, message_params): def test_all_possibilities_de_json_and_to_dict(self, offline_bot, message_params):
new = Message.de_json(message_params.to_dict(), bot) new = Message.de_json(message_params.to_dict(), offline_bot)
assert new.api_kwargs == {} assert new.api_kwargs == {}
assert new.to_dict() == message_params.to_dict() assert new.to_dict() == message_params.to_dict()
@ -579,7 +579,7 @@ class TestMessageWithoutRequest(MessageTestBase):
for slot in new.__slots__: for slot in new.__slots__:
assert not isinstance(new[slot], dict) assert not isinstance(new[slot], dict)
def test_de_json_localization(self, bot, raw_bot, tz_bot): def test_de_json_localization(self, offline_bot, raw_bot, tz_bot):
json_dict = { json_dict = {
"message_id": 12, "message_id": 12,
"from_user": None, "from_user": None,
@ -589,7 +589,7 @@ class TestMessageWithoutRequest(MessageTestBase):
} }
message_raw = Message.de_json(json_dict, raw_bot) message_raw = Message.de_json(json_dict, raw_bot)
message_bot = Message.de_json(json_dict, bot) message_bot = Message.de_json(json_dict, offline_bot)
message_tz = Message.de_json(json_dict, tz_bot) message_tz = Message.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable
@ -609,7 +609,7 @@ class TestMessageWithoutRequest(MessageTestBase):
assert message_bot.edit_date.tzinfo == UTC assert message_bot.edit_date.tzinfo == UTC
assert edit_date_offset == edit_date_tz_bot_offset assert edit_date_offset == edit_date_tz_bot_offset
def test_de_json_api_kwargs_backward_compatibility(self, bot, message_params): def test_de_json_api_kwargs_backward_compatibility(self, offline_bot, message_params):
message_dict = message_params.to_dict() message_dict = message_params.to_dict()
keys = ( keys = (
"user_shared", "user_shared",
@ -622,7 +622,7 @@ class TestMessageWithoutRequest(MessageTestBase):
) )
for key in keys: for key in keys:
message_dict[key] = key message_dict[key] = key
message = Message.de_json(message_dict, bot) message = Message.de_json(message_dict, offline_bot)
assert message.api_kwargs == {key: key for key in keys} assert message.api_kwargs == {key: key for key in keys}
def test_equality(self): def test_equality(self):
@ -2653,10 +2653,10 @@ class TestMessageWithoutRequest(MessageTestBase):
], ],
) )
async def test_default_do_quote( async def test_default_do_quote(
self, bot, message, default_quote, chat_type, expected, monkeypatch self, offline_bot, message, default_quote, chat_type, expected, monkeypatch
): ):
original_bot = message.get_bot() original_bot = message.get_bot()
temp_bot = PytestExtBot(token=bot.token, defaults=Defaults(do_quote=default_quote)) temp_bot = PytestExtBot(token=offline_bot.token, defaults=Defaults(do_quote=default_quote))
message.set_bot(temp_bot) message.set_bot(temp_bot)
async def make_assertion(*_, **kwargs): async def make_assertion(*_, **kwargs):

View file

@ -55,9 +55,9 @@ class TestMessageEntityWithoutRequest(MessageEntityTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = {"type": self.type_, "offset": self.offset, "length": self.length} json_dict = {"type": self.type_, "offset": self.offset, "length": self.length}
entity = MessageEntity.de_json(json_dict, bot) entity = MessageEntity.de_json(json_dict, offline_bot)
assert entity.api_kwargs == {} assert entity.api_kwargs == {}
assert entity.type == self.type_ assert entity.type == self.type_

View file

@ -136,12 +136,12 @@ class TestMessageOriginTypesWithoutRequest:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json_required_args(self, bot, message_origin_type): def test_de_json_required_args(self, offline_bot, message_origin_type):
cls = message_origin_type.__class__ cls = message_origin_type.__class__
assert cls.de_json({}, bot) is None assert cls.de_json({}, offline_bot) is None
json_dict = make_json_dict(message_origin_type) json_dict = make_json_dict(message_origin_type)
const_message_origin = MessageOrigin.de_json(json_dict, bot) const_message_origin = MessageOrigin.de_json(json_dict, offline_bot)
assert const_message_origin.api_kwargs == {} assert const_message_origin.api_kwargs == {}
assert isinstance(const_message_origin, MessageOrigin) assert isinstance(const_message_origin, MessageOrigin)
@ -151,9 +151,9 @@ class TestMessageOriginTypesWithoutRequest:
): ):
assert msg_origin_type_at == const_msg_origin_at assert msg_origin_type_at == const_msg_origin_at
def test_de_json_all_args(self, bot, message_origin_type): def test_de_json_all_args(self, offline_bot, message_origin_type):
json_dict = make_json_dict(message_origin_type, include_optional_args=True) json_dict = make_json_dict(message_origin_type, include_optional_args=True)
const_message_origin = MessageOrigin.de_json(json_dict, bot) const_message_origin = MessageOrigin.de_json(json_dict, offline_bot)
assert const_message_origin.api_kwargs == {} assert const_message_origin.api_kwargs == {}
@ -164,10 +164,12 @@ class TestMessageOriginTypesWithoutRequest:
): ):
assert msg_origin_type_at == const_msg_origin_at assert msg_origin_type_at == const_msg_origin_at
def test_de_json_messageorigin_localization(self, message_origin_type, tz_bot, bot, raw_bot): def test_de_json_messageorigin_localization(
self, message_origin_type, tz_bot, offline_bot, raw_bot
):
json_dict = make_json_dict(message_origin_type, include_optional_args=True) json_dict = make_json_dict(message_origin_type, include_optional_args=True)
msgorigin_raw = MessageOrigin.de_json(json_dict, raw_bot) msgorigin_raw = MessageOrigin.de_json(json_dict, raw_bot)
msgorigin_bot = MessageOrigin.de_json(json_dict, bot) msgorigin_bot = MessageOrigin.de_json(json_dict, offline_bot)
msgorigin_tz = MessageOrigin.de_json(json_dict, tz_bot) msgorigin_tz = MessageOrigin.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable
@ -178,19 +180,19 @@ class TestMessageOriginTypesWithoutRequest:
assert msgorigin_bot.date.tzinfo == UTC assert msgorigin_bot.date.tzinfo == UTC
assert msgorigin_offset == tz_bot_offset assert msgorigin_offset == tz_bot_offset
def test_de_json_invalid_type(self, message_origin_type, bot): def test_de_json_invalid_type(self, message_origin_type, offline_bot):
json_dict = {"type": "invalid", "date": MODefaults.date} json_dict = {"type": "invalid", "date": MODefaults.date}
message_origin_type = MessageOrigin.de_json(json_dict, bot) message_origin_type = MessageOrigin.de_json(json_dict, offline_bot)
assert type(message_origin_type) is MessageOrigin assert type(message_origin_type) is MessageOrigin
assert message_origin_type.type == "invalid" assert message_origin_type.type == "invalid"
def test_de_json_subclass(self, message_origin_type, bot, chat_id): def test_de_json_subclass(self, message_origin_type, offline_bot, chat_id):
"""This makes sure that e.g. MessageOriginChat(data, bot) never returns a """This makes sure that e.g. MessageOriginChat(data, offline_bot) never returns a
MessageOriginUser instance.""" MessageOriginUser instance."""
cls = message_origin_type.__class__ cls = message_origin_type.__class__
json_dict = make_json_dict(message_origin_type, True) json_dict = make_json_dict(message_origin_type, True)
assert type(cls.de_json(json_dict, bot)) is cls assert type(cls.de_json(json_dict, offline_bot)) is cls
def test_to_dict(self, message_origin_type): def test_to_dict(self, message_origin_type):
message_origin_dict = message_origin_type.to_dict() message_origin_dict = message_origin_type.to_dict()

View file

@ -150,7 +150,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, pm_scope_class_and_type): def test_de_json(self, offline_bot, pm_scope_class_and_type):
cls = pm_scope_class_and_type[0] cls = pm_scope_class_and_type[0]
type_ = pm_scope_class_and_type[1] type_ = pm_scope_class_and_type[1]
@ -162,7 +162,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
"video": self.video.to_dict(), "video": self.video.to_dict(),
"photo": [p.to_dict() for p in self.photo], "photo": [p.to_dict() for p in self.photo],
} }
pm = PaidMedia.de_json(json_dict, bot) pm = PaidMedia.de_json(json_dict, offline_bot)
assert set(pm.api_kwargs.keys()) == { assert set(pm.api_kwargs.keys()) == {
"width", "width",
"height", "height",
@ -183,10 +183,10 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
if "photo" in cls.__slots__: if "photo" in cls.__slots__:
assert pm.photo == self.photo assert pm.photo == self.photo
assert cls.de_json(None, bot) is None assert cls.de_json(None, offline_bot) is None
assert PaidMedia.de_json({}, bot) is None assert PaidMedia.de_json({}, offline_bot) is None
def test_de_json_invalid_type(self, bot): def test_de_json_invalid_type(self, offline_bot):
json_dict = { json_dict = {
"type": "invalid", "type": "invalid",
"width": self.width, "width": self.width,
@ -195,7 +195,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
"video": self.video.to_dict(), "video": self.video.to_dict(),
"photo": [p.to_dict() for p in self.photo], "photo": [p.to_dict() for p in self.photo],
} }
pm = PaidMedia.de_json(json_dict, bot) pm = PaidMedia.de_json(json_dict, offline_bot)
assert pm.api_kwargs == { assert pm.api_kwargs == {
"width": self.width, "width": self.width,
"height": self.height, "height": self.height,
@ -207,7 +207,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
assert type(pm) is PaidMedia assert type(pm) is PaidMedia
assert pm.type == "invalid" assert pm.type == "invalid"
def test_de_json_subclass(self, pm_scope_class, bot): def test_de_json_subclass(self, pm_scope_class, offline_bot):
"""This makes sure that e.g. PaidMediaPreivew(data) never returns a """This makes sure that e.g. PaidMediaPreivew(data) never returns a
TransactionPartnerPhoto instance.""" TransactionPartnerPhoto instance."""
json_dict = { json_dict = {
@ -218,7 +218,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
"video": self.video.to_dict(), "video": self.video.to_dict(),
"photo": [p.to_dict() for p in self.photo], "photo": [p.to_dict() for p in self.photo],
} }
assert type(pm_scope_class.de_json(json_dict, bot)) is pm_scope_class assert type(pm_scope_class.de_json(json_dict, offline_bot)) is pm_scope_class
def test_to_dict(self, paid_media): def test_to_dict(self, paid_media):
pm_dict = paid_media.to_dict() pm_dict = paid_media.to_dict()
@ -238,7 +238,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
assert type(PaidMedia("video").type) is PaidMediaType assert type(PaidMedia("video").type) is PaidMediaType
assert PaidMedia("unknown").type == "unknown" assert PaidMedia("unknown").type == "unknown"
def test_equality(self, paid_media, bot): def test_equality(self, paid_media, offline_bot):
a = PaidMedia("base_type") a = PaidMedia("base_type")
b = PaidMedia("base_type") b = PaidMedia("base_type")
c = paid_media c = paid_media
@ -266,7 +266,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
if hasattr(c, "video"): if hasattr(c, "video"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["video"] = Video("different", "d2", 1, 1, 1).to_dict() json_dict["video"] = Video("different", "d2", 1, 1, 1).to_dict()
f = c.__class__.de_json(json_dict, bot) f = c.__class__.de_json(json_dict, offline_bot)
assert c != f assert c != f
assert hash(c) != hash(f) assert hash(c) != hash(f)
@ -274,7 +274,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase):
if hasattr(c, "photo"): if hasattr(c, "photo"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["photo"] = [PhotoSize("different", "d2", 1, 1, 1).to_dict()] json_dict["photo"] = [PhotoSize("different", "d2", 1, 1, 1).to_dict()]
f = c.__class__.de_json(json_dict, bot) f = c.__class__.de_json(json_dict, offline_bot)
assert c != f assert c != f
assert hash(c) != hash(f) assert hash(c) != hash(f)
@ -292,13 +292,13 @@ class TestPaidMediaInfoWithoutRequest(PaidMediaInfoTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"star_count": self.star_count, "star_count": self.star_count,
"paid_media": [t.to_dict() for t in self.paid_media], "paid_media": [t.to_dict() for t in self.paid_media],
} }
pmi = PaidMediaInfo.de_json(json_dict, bot) pmi = PaidMediaInfo.de_json(json_dict, offline_bot)
pmi_none = PaidMediaInfo.de_json(None, bot) pmi_none = PaidMediaInfo.de_json(None, offline_bot)
assert pmi.paid_media == tuple(self.paid_media) assert pmi.paid_media == tuple(self.paid_media)
assert pmi.star_count == self.star_count assert pmi.star_count == self.star_count
assert pmi_none is None assert pmi_none is None

View file

@ -305,7 +305,7 @@ class PollTestBase:
class TestPollWithoutRequest(PollTestBase): class TestPollWithoutRequest(PollTestBase):
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"question": self.question, "question": self.question,
@ -321,7 +321,7 @@ class TestPollWithoutRequest(PollTestBase):
"close_date": to_timestamp(self.close_date), "close_date": to_timestamp(self.close_date),
"question_entities": [e.to_dict() for e in self.question_entities], "question_entities": [e.to_dict() for e in self.question_entities],
} }
poll = Poll.de_json(json_dict, bot) poll = Poll.de_json(json_dict, offline_bot)
assert poll.api_kwargs == {} assert poll.api_kwargs == {}
assert poll.id == self.id_ assert poll.id == self.id_
@ -343,7 +343,7 @@ class TestPollWithoutRequest(PollTestBase):
assert to_timestamp(poll.close_date) == to_timestamp(self.close_date) assert to_timestamp(poll.close_date) == to_timestamp(self.close_date)
assert poll.question_entities == tuple(self.question_entities) assert poll.question_entities == tuple(self.question_entities)
def test_de_json_localization(self, tz_bot, bot, raw_bot): def test_de_json_localization(self, tz_bot, offline_bot, raw_bot):
json_dict = { json_dict = {
"id": self.id_, "id": self.id_,
"question": self.question, "question": self.question,
@ -361,7 +361,7 @@ class TestPollWithoutRequest(PollTestBase):
} }
poll_raw = Poll.de_json(json_dict, raw_bot) poll_raw = Poll.de_json(json_dict, raw_bot)
poll_bot = Poll.de_json(json_dict, bot) poll_bot = Poll.de_json(json_dict, offline_bot)
poll_bot_tz = Poll.de_json(json_dict, tz_bot) poll_bot_tz = Poll.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable

View file

@ -44,13 +44,13 @@ class TestProximityAlertTriggeredWithoutRequest(ProximityAlertTriggeredTestBase)
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"traveler": self.traveler.to_dict(), "traveler": self.traveler.to_dict(),
"watcher": self.watcher.to_dict(), "watcher": self.watcher.to_dict(),
"distance": self.distance, "distance": self.distance,
} }
proximity_alert_triggered = ProximityAlertTriggered.de_json(json_dict, bot) proximity_alert_triggered = ProximityAlertTriggered.de_json(json_dict, offline_bot)
assert proximity_alert_triggered.api_kwargs == {} assert proximity_alert_triggered.api_kwargs == {}
assert proximity_alert_triggered.traveler == self.traveler assert proximity_alert_triggered.traveler == self.traveler

View file

@ -115,13 +115,13 @@ class TestReactionTypesWithoutRequest:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json_required_args(self, bot, reaction_type): def test_de_json_required_args(self, offline_bot, reaction_type):
cls = reaction_type.__class__ cls = reaction_type.__class__
assert cls.de_json(None, bot) is None assert cls.de_json(None, offline_bot) is None
assert ReactionType.de_json({}, bot) is None assert ReactionType.de_json({}, offline_bot) is None
json_dict = make_json_dict(reaction_type) json_dict = make_json_dict(reaction_type)
const_reaction_type = ReactionType.de_json(json_dict, bot) const_reaction_type = ReactionType.de_json(json_dict, offline_bot)
assert const_reaction_type.api_kwargs == {} assert const_reaction_type.api_kwargs == {}
assert isinstance(const_reaction_type, ReactionType) assert isinstance(const_reaction_type, ReactionType)
@ -131,9 +131,9 @@ class TestReactionTypesWithoutRequest:
): ):
assert reaction_type_at == const_reaction_type_at assert reaction_type_at == const_reaction_type_at
def test_de_json_all_args(self, bot, reaction_type): def test_de_json_all_args(self, offline_bot, reaction_type):
json_dict = make_json_dict(reaction_type, include_optional_args=True) json_dict = make_json_dict(reaction_type, include_optional_args=True)
const_reaction_type = ReactionType.de_json(json_dict, bot) const_reaction_type = ReactionType.de_json(json_dict, offline_bot)
assert const_reaction_type.api_kwargs == {} assert const_reaction_type.api_kwargs == {}
assert isinstance(const_reaction_type, ReactionType) assert isinstance(const_reaction_type, ReactionType)
@ -141,19 +141,19 @@ class TestReactionTypesWithoutRequest:
for c_mem_type_at, const_c_mem_at in iter_args(reaction_type, const_reaction_type, True): for c_mem_type_at, const_c_mem_at in iter_args(reaction_type, const_reaction_type, True):
assert c_mem_type_at == const_c_mem_at assert c_mem_type_at == const_c_mem_at
def test_de_json_invalid_type(self, bot, reaction_type): def test_de_json_invalid_type(self, offline_bot, reaction_type):
json_dict = {"type": "invalid"} json_dict = {"type": "invalid"}
reaction_type = ReactionType.de_json(json_dict, bot) reaction_type = ReactionType.de_json(json_dict, offline_bot)
assert type(reaction_type) is ReactionType assert type(reaction_type) is ReactionType
assert reaction_type.type == "invalid" assert reaction_type.type == "invalid"
def test_de_json_subclass(self, reaction_type, bot, chat_id): def test_de_json_subclass(self, reaction_type, offline_bot, chat_id):
"""This makes sure that e.g. ReactionTypeEmoji(data, bot) never returns a """This makes sure that e.g. ReactionTypeEmoji(data, offline_bot) never returns a
ReactionTypeCustomEmoji instance.""" ReactionTypeCustomEmoji instance."""
cls = reaction_type.__class__ cls = reaction_type.__class__
json_dict = make_json_dict(reaction_type, True) json_dict = make_json_dict(reaction_type, True)
assert type(cls.de_json(json_dict, bot)) is cls assert type(cls.de_json(json_dict, offline_bot)) is cls
def test_to_dict(self, reaction_type): def test_to_dict(self, reaction_type):
reaction_type_dict = reaction_type.to_dict() reaction_type_dict = reaction_type.to_dict()
@ -237,13 +237,13 @@ class TestReactionCountWithoutRequest:
set(mro_slots(reaction_count)) set(mro_slots(reaction_count))
), "duplicate slot" ), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"type": self.type.to_dict(), "type": self.type.to_dict(),
"total_count": self.total_count, "total_count": self.total_count,
} }
reaction_count = ReactionCount.de_json(json_dict, bot) reaction_count = ReactionCount.de_json(json_dict, offline_bot)
assert reaction_count.api_kwargs == {} assert reaction_count.api_kwargs == {}
assert isinstance(reaction_count, ReactionCount) assert isinstance(reaction_count, ReactionCount)
@ -252,7 +252,7 @@ class TestReactionCountWithoutRequest:
assert reaction_count.type.emoji == self.type.emoji assert reaction_count.type.emoji == self.type.emoji
assert reaction_count.total_count == self.total_count assert reaction_count.total_count == self.total_count
assert ReactionCount.de_json(None, bot) is None assert ReactionCount.de_json(None, offline_bot) is None
def test_to_dict(self, reaction_count): def test_to_dict(self, reaction_count):
reaction_count_dict = reaction_count.to_dict() reaction_count_dict = reaction_count.to_dict()

View file

@ -73,7 +73,7 @@ class TestExternalReplyInfoWithoutRequest(ExternalReplyInfoTestBase):
set(mro_slots(external_reply_info)) set(mro_slots(external_reply_info))
), "duplicate slot" ), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"origin": self.origin.to_dict(), "origin": self.origin.to_dict(),
"chat": self.chat.to_dict(), "chat": self.chat.to_dict(),
@ -83,7 +83,7 @@ class TestExternalReplyInfoWithoutRequest(ExternalReplyInfoTestBase):
"paid_media": self.paid_media.to_dict(), "paid_media": self.paid_media.to_dict(),
} }
external_reply_info = ExternalReplyInfo.de_json(json_dict, bot) external_reply_info = ExternalReplyInfo.de_json(json_dict, offline_bot)
assert external_reply_info.api_kwargs == {} assert external_reply_info.api_kwargs == {}
assert external_reply_info.origin == self.origin assert external_reply_info.origin == self.origin
@ -93,7 +93,7 @@ class TestExternalReplyInfoWithoutRequest(ExternalReplyInfoTestBase):
assert external_reply_info.giveaway == self.giveaway assert external_reply_info.giveaway == self.giveaway
assert external_reply_info.paid_media == self.paid_media assert external_reply_info.paid_media == self.paid_media
assert ExternalReplyInfo.de_json(None, bot) is None assert ExternalReplyInfo.de_json(None, offline_bot) is None
def test_to_dict(self, external_reply_info): def test_to_dict(self, external_reply_info):
ext_reply_info_dict = external_reply_info.to_dict() ext_reply_info_dict = external_reply_info.to_dict()
@ -151,7 +151,7 @@ class TestTextQuoteWithoutRequest(TextQuoteTestBase):
assert getattr(text_quote, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(text_quote, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(text_quote)) == len(set(mro_slots(text_quote))), "duplicate slot" assert len(mro_slots(text_quote)) == len(set(mro_slots(text_quote))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"text": self.text, "text": self.text,
"position": self.position, "position": self.position,
@ -159,7 +159,7 @@ class TestTextQuoteWithoutRequest(TextQuoteTestBase):
"is_manual": self.is_manual, "is_manual": self.is_manual,
} }
text_quote = TextQuote.de_json(json_dict, bot) text_quote = TextQuote.de_json(json_dict, offline_bot)
assert text_quote.api_kwargs == {} assert text_quote.api_kwargs == {}
assert text_quote.text == self.text assert text_quote.text == self.text
@ -167,7 +167,7 @@ class TestTextQuoteWithoutRequest(TextQuoteTestBase):
assert text_quote.entities == tuple(self.entities) assert text_quote.entities == tuple(self.entities)
assert text_quote.is_manual == self.is_manual assert text_quote.is_manual == self.is_manual
assert TextQuote.de_json(None, bot) is None assert TextQuote.de_json(None, offline_bot) is None
def test_to_dict(self, text_quote): def test_to_dict(self, text_quote):
text_quote_dict = text_quote.to_dict() text_quote_dict = text_quote.to_dict()
@ -233,7 +233,7 @@ class TestReplyParametersWithoutRequest(ReplyParametersTestBase):
set(mro_slots(reply_parameters)) set(mro_slots(reply_parameters))
), "duplicate slot" ), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"message_id": self.message_id, "message_id": self.message_id,
"chat_id": self.chat_id, "chat_id": self.chat_id,
@ -244,7 +244,7 @@ class TestReplyParametersWithoutRequest(ReplyParametersTestBase):
"quote_position": self.quote_position, "quote_position": self.quote_position,
} }
reply_parameters = ReplyParameters.de_json(json_dict, bot) reply_parameters = ReplyParameters.de_json(json_dict, offline_bot)
assert reply_parameters.api_kwargs == {} assert reply_parameters.api_kwargs == {}
assert reply_parameters.message_id == self.message_id assert reply_parameters.message_id == self.message_id
@ -255,7 +255,7 @@ class TestReplyParametersWithoutRequest(ReplyParametersTestBase):
assert reply_parameters.quote_entities == tuple(self.quote_entities) assert reply_parameters.quote_entities == tuple(self.quote_entities)
assert reply_parameters.quote_position == self.quote_position assert reply_parameters.quote_position == self.quote_position
assert ReplyParameters.de_json(None, bot) is None assert ReplyParameters.de_json(None, offline_bot) is None
def test_to_dict(self, reply_parameters): def test_to_dict(self, reply_parameters):
reply_parameters_dict = reply_parameters.to_dict() reply_parameters_dict = reply_parameters.to_dict()

View file

@ -45,7 +45,7 @@ class TestSentWebAppMessageWithoutRequest(SentWebAppMessageTestBase):
assert isinstance(sent_web_app_message_dict, dict) assert isinstance(sent_web_app_message_dict, dict)
assert sent_web_app_message_dict["inline_message_id"] == self.inline_message_id assert sent_web_app_message_dict["inline_message_id"] == self.inline_message_id
def test_de_json(self, bot): def test_de_json(self, offline_bot):
data = {"inline_message_id": self.inline_message_id} data = {"inline_message_id": self.inline_message_id}
m = SentWebAppMessage.de_json(data, None) m = SentWebAppMessage.de_json(data, None)
assert m.api_kwargs == {} assert m.api_kwargs == {}

View file

@ -47,19 +47,19 @@ class TestUsersSharedWithoutRequest(UsersSharedTestBase):
assert users_shared_dict["request_id"] == self.request_id assert users_shared_dict["request_id"] == self.request_id
assert users_shared_dict["users"] == [user.to_dict() for user in self.users] assert users_shared_dict["users"] == [user.to_dict() for user in self.users]
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"request_id": self.request_id, "request_id": self.request_id,
"users": [user.to_dict() for user in self.users], "users": [user.to_dict() for user in self.users],
"user_ids": self.user_ids, "user_ids": self.user_ids,
} }
users_shared = UsersShared.de_json(json_dict, bot) users_shared = UsersShared.de_json(json_dict, offline_bot)
assert users_shared.api_kwargs == {"user_ids": self.user_ids} assert users_shared.api_kwargs == {"user_ids": self.user_ids}
assert users_shared.request_id == self.request_id assert users_shared.request_id == self.request_id
assert users_shared.users == self.users assert users_shared.users == self.users
assert UsersShared.de_json({}, bot) is None assert UsersShared.de_json({}, offline_bot) is None
def test_equality(self): def test_equality(self):
a = UsersShared(self.request_id, users=self.users) a = UsersShared(self.request_id, users=self.users)
@ -108,12 +108,12 @@ class TestChatSharedWithoutRequest(ChatSharedTestBase):
assert chat_shared_dict["request_id"] == self.request_id assert chat_shared_dict["request_id"] == self.request_id
assert chat_shared_dict["chat_id"] == self.chat_id assert chat_shared_dict["chat_id"] == self.chat_id
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"request_id": self.request_id, "request_id": self.request_id,
"chat_id": self.chat_id, "chat_id": self.chat_id,
} }
chat_shared = ChatShared.de_json(json_dict, bot) chat_shared = ChatShared.de_json(json_dict, offline_bot)
assert chat_shared.api_kwargs == {} assert chat_shared.api_kwargs == {}
assert chat_shared.request_id == self.request_id assert chat_shared.request_id == self.request_id
@ -178,12 +178,12 @@ class TestSharedUserWithoutRequest(SharedUserTestBase):
assert shared_user_dict["username"] == self.username assert shared_user_dict["username"] == self.username
assert shared_user_dict["photo"] == [photo.to_dict() for photo in self.photo] assert shared_user_dict["photo"] == [photo.to_dict() for photo in self.photo]
def test_de_json_required(self, bot): def test_de_json_required(self, offline_bot):
json_dict = { json_dict = {
"user_id": self.user_id, "user_id": self.user_id,
"first_name": self.first_name, "first_name": self.first_name,
} }
shared_user = SharedUser.de_json(json_dict, bot) shared_user = SharedUser.de_json(json_dict, offline_bot)
assert shared_user.api_kwargs == {} assert shared_user.api_kwargs == {}
assert shared_user.user_id == self.user_id assert shared_user.user_id == self.user_id
@ -192,7 +192,7 @@ class TestSharedUserWithoutRequest(SharedUserTestBase):
assert shared_user.username is None assert shared_user.username is None
assert shared_user.photo == () assert shared_user.photo == ()
def test_de_json_all(self, bot): def test_de_json_all(self, offline_bot):
json_dict = { json_dict = {
"user_id": self.user_id, "user_id": self.user_id,
"first_name": self.first_name, "first_name": self.first_name,
@ -200,7 +200,7 @@ class TestSharedUserWithoutRequest(SharedUserTestBase):
"username": self.username, "username": self.username,
"photo": [photo.to_dict() for photo in self.photo], "photo": [photo.to_dict() for photo in self.photo],
} }
shared_user = SharedUser.de_json(json_dict, bot) shared_user = SharedUser.de_json(json_dict, offline_bot)
assert shared_user.api_kwargs == {} assert shared_user.api_kwargs == {}
assert shared_user.user_id == self.user_id assert shared_user.user_id == self.user_id
@ -209,7 +209,7 @@ class TestSharedUserWithoutRequest(SharedUserTestBase):
assert shared_user.username == self.username assert shared_user.username == self.username
assert shared_user.photo == self.photo assert shared_user.photo == self.photo
assert SharedUser.de_json({}, bot) is None assert SharedUser.de_json({}, offline_bot) is None
def test_equality(self, chat_shared): def test_equality(self, chat_shared):
a = SharedUser( a = SharedUser(

View file

@ -253,7 +253,7 @@ class TestStarTransactionWithoutRequest(StarTransactionTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"id": self.id, "id": self.id,
"amount": self.amount, "amount": self.amount,
@ -261,8 +261,8 @@ class TestStarTransactionWithoutRequest(StarTransactionTestBase):
"source": self.source.to_dict(), "source": self.source.to_dict(),
"receiver": self.receiver.to_dict(), "receiver": self.receiver.to_dict(),
} }
st = StarTransaction.de_json(json_dict, bot) st = StarTransaction.de_json(json_dict, offline_bot)
st_none = StarTransaction.de_json(None, bot) st_none = StarTransaction.de_json(None, offline_bot)
assert st.api_kwargs == {} assert st.api_kwargs == {}
assert st.id == self.id assert st.id == self.id
assert st.amount == self.amount assert st.amount == self.amount
@ -271,10 +271,10 @@ class TestStarTransactionWithoutRequest(StarTransactionTestBase):
assert st.receiver == self.receiver assert st.receiver == self.receiver
assert st_none is None assert st_none is None
def test_de_json_star_transaction_localization(self, tz_bot, bot, raw_bot): def test_de_json_star_transaction_localization(self, tz_bot, offline_bot, raw_bot):
json_dict = star_transaction().to_dict() json_dict = star_transaction().to_dict()
st_raw = StarTransaction.de_json(json_dict, raw_bot) st_raw = StarTransaction.de_json(json_dict, raw_bot)
st_bot = StarTransaction.de_json(json_dict, bot) st_bot = StarTransaction.de_json(json_dict, offline_bot)
st_tz = StarTransaction.de_json(json_dict, tz_bot) st_tz = StarTransaction.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable
@ -343,12 +343,12 @@ class TestStarTransactionsWithoutRequest(StarTransactionsTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"transactions": [t.to_dict() for t in self.transactions], "transactions": [t.to_dict() for t in self.transactions],
} }
st = StarTransactions.de_json(json_dict, bot) st = StarTransactions.de_json(json_dict, offline_bot)
st_none = StarTransactions.de_json(None, bot) st_none = StarTransactions.de_json(None, offline_bot)
assert st.api_kwargs == {} assert st.api_kwargs == {}
assert st.transactions == tuple(self.transactions) assert st.transactions == tuple(self.transactions)
assert st_none is None assert st_none is None
@ -390,7 +390,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, tp_scope_class_and_type): def test_de_json(self, offline_bot, tp_scope_class_and_type):
cls = tp_scope_class_and_type[0] cls = tp_scope_class_and_type[0]
type_ = tp_scope_class_and_type[1] type_ = tp_scope_class_and_type[1]
@ -400,7 +400,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase):
"withdrawal_state": self.withdrawal_state.to_dict(), "withdrawal_state": self.withdrawal_state.to_dict(),
"user": self.user.to_dict(), "user": self.user.to_dict(),
} }
tp = TransactionPartner.de_json(json_dict, bot) tp = TransactionPartner.de_json(json_dict, offline_bot)
assert set(tp.api_kwargs.keys()) == {"user", "withdrawal_state", "invoice_payload"} - set( assert set(tp.api_kwargs.keys()) == {"user", "withdrawal_state", "invoice_payload"} - set(
cls.__slots__ cls.__slots__
) )
@ -414,17 +414,17 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase):
assert tp.user == self.user assert tp.user == self.user
assert tp.invoice_payload == self.invoice_payload assert tp.invoice_payload == self.invoice_payload
assert cls.de_json(None, bot) is None assert cls.de_json(None, offline_bot) is None
assert TransactionPartner.de_json({}, bot) is None assert TransactionPartner.de_json({}, offline_bot) is None
def test_de_json_invalid_type(self, bot): def test_de_json_invalid_type(self, offline_bot):
json_dict = { json_dict = {
"type": "invalid", "type": "invalid",
"invoice_payload": self.invoice_payload, "invoice_payload": self.invoice_payload,
"withdrawal_state": self.withdrawal_state.to_dict(), "withdrawal_state": self.withdrawal_state.to_dict(),
"user": self.user.to_dict(), "user": self.user.to_dict(),
} }
tp = TransactionPartner.de_json(json_dict, bot) tp = TransactionPartner.de_json(json_dict, offline_bot)
assert tp.api_kwargs == { assert tp.api_kwargs == {
"withdrawal_state": self.withdrawal_state.to_dict(), "withdrawal_state": self.withdrawal_state.to_dict(),
"user": self.user.to_dict(), "user": self.user.to_dict(),
@ -434,7 +434,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase):
assert type(tp) is TransactionPartner assert type(tp) is TransactionPartner
assert tp.type == "invalid" assert tp.type == "invalid"
def test_de_json_subclass(self, tp_scope_class, bot): def test_de_json_subclass(self, tp_scope_class, offline_bot):
"""This makes sure that e.g. TransactionPartnerUser(data) never returns a """This makes sure that e.g. TransactionPartnerUser(data) never returns a
TransactionPartnerFragment instance.""" TransactionPartnerFragment instance."""
json_dict = { json_dict = {
@ -443,7 +443,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase):
"withdrawal_state": self.withdrawal_state.to_dict(), "withdrawal_state": self.withdrawal_state.to_dict(),
"user": self.user.to_dict(), "user": self.user.to_dict(),
} }
assert type(tp_scope_class.de_json(json_dict, bot)) is tp_scope_class assert type(tp_scope_class.de_json(json_dict, offline_bot)) is tp_scope_class
def test_to_dict(self, transaction_partner): def test_to_dict(self, transaction_partner):
tp_dict = transaction_partner.to_dict() tp_dict = transaction_partner.to_dict()
@ -460,7 +460,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase):
assert type(TransactionPartner("other").type) is TransactionPartnerType assert type(TransactionPartner("other").type) is TransactionPartnerType
assert TransactionPartner("unknown").type == "unknown" assert TransactionPartner("unknown").type == "unknown"
def test_equality(self, transaction_partner, bot): def test_equality(self, transaction_partner, offline_bot):
a = TransactionPartner("base_type") a = TransactionPartner("base_type")
b = TransactionPartner("base_type") b = TransactionPartner("base_type")
c = transaction_partner c = transaction_partner
@ -488,7 +488,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase):
if hasattr(c, "user"): if hasattr(c, "user"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["user"] = User(2, "something", True).to_dict() json_dict["user"] = User(2, "something", True).to_dict()
f = c.__class__.de_json(json_dict, bot) f = c.__class__.de_json(json_dict, offline_bot)
assert c != f assert c != f
assert hash(c) != hash(f) assert hash(c) != hash(f)
@ -506,7 +506,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot, rws_scope_class_and_type): def test_de_json(self, offline_bot, rws_scope_class_and_type):
cls = rws_scope_class_and_type[0] cls = rws_scope_class_and_type[0]
type_ = rws_scope_class_and_type[1] type_ = rws_scope_class_and_type[1]
@ -515,7 +515,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
"date": to_timestamp(self.date), "date": to_timestamp(self.date),
"url": self.url, "url": self.url,
} }
rws = RevenueWithdrawalState.de_json(json_dict, bot) rws = RevenueWithdrawalState.de_json(json_dict, offline_bot)
assert set(rws.api_kwargs.keys()) == {"date", "url"} - set(cls.__slots__) assert set(rws.api_kwargs.keys()) == {"date", "url"} - set(cls.__slots__)
assert isinstance(rws, RevenueWithdrawalState) assert isinstance(rws, RevenueWithdrawalState)
@ -526,16 +526,16 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
if "url" in cls.__slots__: if "url" in cls.__slots__:
assert rws.url == self.url assert rws.url == self.url
assert cls.de_json(None, bot) is None assert cls.de_json(None, offline_bot) is None
assert RevenueWithdrawalState.de_json({}, bot) is None assert RevenueWithdrawalState.de_json({}, offline_bot) is None
def test_de_json_invalid_type(self, bot): def test_de_json_invalid_type(self, offline_bot):
json_dict = { json_dict = {
"type": "invalid", "type": "invalid",
"date": to_timestamp(self.date), "date": to_timestamp(self.date),
"url": self.url, "url": self.url,
} }
rws = RevenueWithdrawalState.de_json(json_dict, bot) rws = RevenueWithdrawalState.de_json(json_dict, offline_bot)
assert rws.api_kwargs == { assert rws.api_kwargs == {
"date": to_timestamp(self.date), "date": to_timestamp(self.date),
"url": self.url, "url": self.url,
@ -544,7 +544,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
assert type(rws) is RevenueWithdrawalState assert type(rws) is RevenueWithdrawalState
assert rws.type == "invalid" assert rws.type == "invalid"
def test_de_json_subclass(self, rws_scope_class, bot): def test_de_json_subclass(self, rws_scope_class, offline_bot):
"""This makes sure that e.g. RevenueWithdrawalState(data) never returns a """This makes sure that e.g. RevenueWithdrawalState(data) never returns a
RevenueWithdrawalStateFailed instance.""" RevenueWithdrawalStateFailed instance."""
json_dict = { json_dict = {
@ -552,7 +552,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
"date": to_timestamp(self.date), "date": to_timestamp(self.date),
"url": self.url, "url": self.url,
} }
assert type(rws_scope_class.de_json(json_dict, bot)) is rws_scope_class assert type(rws_scope_class.de_json(json_dict, offline_bot)) is rws_scope_class
def test_to_dict(self, revenue_withdrawal_state): def test_to_dict(self, revenue_withdrawal_state):
rws_dict = revenue_withdrawal_state.to_dict() rws_dict = revenue_withdrawal_state.to_dict()
@ -568,7 +568,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
assert type(RevenueWithdrawalState("failed").type) is RevenueWithdrawalStateType assert type(RevenueWithdrawalState("failed").type) is RevenueWithdrawalStateType
assert RevenueWithdrawalState("unknown").type == "unknown" assert RevenueWithdrawalState("unknown").type == "unknown"
def test_equality(self, revenue_withdrawal_state, bot): def test_equality(self, revenue_withdrawal_state, offline_bot):
a = RevenueWithdrawalState("base_type") a = RevenueWithdrawalState("base_type")
b = RevenueWithdrawalState("base_type") b = RevenueWithdrawalState("base_type")
c = revenue_withdrawal_state c = revenue_withdrawal_state
@ -596,7 +596,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
if hasattr(c, "url"): if hasattr(c, "url"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["url"] = "something" json_dict["url"] = "something"
f = c.__class__.de_json(json_dict, bot) f = c.__class__.de_json(json_dict, offline_bot)
assert c == f assert c == f
assert hash(c) == hash(f) assert hash(c) == hash(f)
@ -604,7 +604,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase):
if hasattr(c, "date"): if hasattr(c, "date"):
json_dict = c.to_dict() json_dict = c.to_dict()
json_dict["date"] = to_timestamp(datetime.datetime.utcnow()) json_dict["date"] = to_timestamp(datetime.datetime.utcnow())
f = c.__class__.de_json(json_dict, bot) f = c.__class__.de_json(json_dict, offline_bot)
assert c != f assert c != f
assert hash(c) != hash(f) assert hash(c) != hash(f)

View file

@ -38,14 +38,14 @@ class TestStoryWithoutRequest(StoryTestBase):
assert getattr(story, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(story, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(story)) == len(set(mro_slots(story))), "duplicate slot" assert len(mro_slots(story)) == len(set(mro_slots(story))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = {"chat": self.chat.to_dict(), "id": self.id} json_dict = {"chat": self.chat.to_dict(), "id": self.id}
story = Story.de_json(json_dict, bot) story = Story.de_json(json_dict, offline_bot)
assert story.api_kwargs == {} assert story.api_kwargs == {}
assert story.chat == self.chat assert story.chat == self.chat
assert story.id == self.id assert story.id == self.id
assert isinstance(story, Story) assert isinstance(story, Story)
assert Story.de_json(None, bot) is None assert Story.de_json(None, offline_bot) is None
def test_to_dict(self, story): def test_to_dict(self, story):
story_dict = story.to_dict() story_dict = story.to_dict()

View file

@ -227,11 +227,11 @@ class TestUpdateWithoutRequest(UpdateTestBase):
assert len(mro_slots(update)) == len(set(mro_slots(update))), "duplicate slot" assert len(mro_slots(update)) == len(set(mro_slots(update))), "duplicate slot"
@pytest.mark.parametrize("paramdict", argvalues=params, ids=ids) @pytest.mark.parametrize("paramdict", argvalues=params, ids=ids)
def test_de_json(self, bot, paramdict): def test_de_json(self, offline_bot, paramdict):
json_dict = {"update_id": self.update_id} json_dict = {"update_id": self.update_id}
# Convert the single update 'item' to a dict of that item and apply it to the json_dict # Convert the single update 'item' to a dict of that item and apply it to the json_dict
json_dict.update({k: v.to_dict() for k, v in paramdict.items()}) json_dict.update({k: v.to_dict() for k, v in paramdict.items()})
update = Update.de_json(json_dict, bot) update = Update.de_json(json_dict, offline_bot)
assert update.api_kwargs == {} assert update.api_kwargs == {}
assert update.update_id == self.update_id assert update.update_id == self.update_id
@ -244,8 +244,8 @@ class TestUpdateWithoutRequest(UpdateTestBase):
assert getattr(update, _type) == paramdict[_type] assert getattr(update, _type) == paramdict[_type]
assert i == 1 assert i == 1
def test_update_de_json_empty(self, bot): def test_update_de_json_empty(self, offline_bot):
update = Update.de_json(None, bot) update = Update.de_json(None, offline_bot)
assert update is None assert update is None

View file

@ -91,8 +91,8 @@ class TestUserWithoutRequest(UserTestBase):
assert getattr(user, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(user, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(user)) == len(set(mro_slots(user))), "duplicate slot" assert len(mro_slots(user)) == len(set(mro_slots(user))), "duplicate slot"
def test_de_json(self, json_dict, bot): def test_de_json(self, json_dict, offline_bot):
user = User.de_json(json_dict, bot) user = User.de_json(json_dict, offline_bot)
assert user.api_kwargs == {} assert user.api_kwargs == {}
assert user.id == self.id_ assert user.id == self.id_

View file

@ -41,9 +41,9 @@ class TestUserProfilePhotosWithoutRequest(UserProfilePhotosTestBase):
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = {"total_count": 2, "photos": [[y.to_dict() for y in x] for x in self.photos]} json_dict = {"total_count": 2, "photos": [[y.to_dict() for y in x] for x in self.photos]}
user_profile_photos = UserProfilePhotos.de_json(json_dict, bot) user_profile_photos = UserProfilePhotos.de_json(json_dict, offline_bot)
assert user_profile_photos.api_kwargs == {} assert user_profile_photos.api_kwargs == {}
assert user_profile_photos.total_count == self.total_count assert user_profile_photos.total_count == self.total_count
assert user_profile_photos.photos == tuple(tuple(p) for p in self.photos) assert user_profile_photos.photos == tuple(tuple(p) for p in self.photos)

View file

@ -105,9 +105,9 @@ class TestVideoChatParticipantsInvitedWithoutRequest:
assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'" assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(action)) == len(set(mro_slots(action))), "duplicate slot" assert len(mro_slots(action)) == len(set(mro_slots(action))), "duplicate slot"
def test_de_json(self, user1, user2, bot): def test_de_json(self, user1, user2, offline_bot):
json_data = {"users": [user1.to_dict(), user2.to_dict()]} json_data = {"users": [user1.to_dict(), user2.to_dict()]}
video_chat_participants = VideoChatParticipantsInvited.de_json(json_data, bot) video_chat_participants = VideoChatParticipantsInvited.de_json(json_data, offline_bot)
assert video_chat_participants.api_kwargs == {} assert video_chat_participants.api_kwargs == {}
assert isinstance(video_chat_participants.users, tuple) assert isinstance(video_chat_participants.users, tuple)
@ -161,20 +161,20 @@ class TestVideoChatScheduledWithoutRequest:
def test_expected_values(self): def test_expected_values(self):
assert VideoChatScheduled(self.start_date).start_date == self.start_date assert VideoChatScheduled(self.start_date).start_date == self.start_date
def test_de_json(self, bot): def test_de_json(self, offline_bot):
assert VideoChatScheduled.de_json({}, bot=bot) is None assert VideoChatScheduled.de_json({}, bot=offline_bot) is None
json_dict = {"start_date": to_timestamp(self.start_date)} json_dict = {"start_date": to_timestamp(self.start_date)}
video_chat_scheduled = VideoChatScheduled.de_json(json_dict, bot) video_chat_scheduled = VideoChatScheduled.de_json(json_dict, offline_bot)
assert video_chat_scheduled.api_kwargs == {} assert video_chat_scheduled.api_kwargs == {}
assert abs(video_chat_scheduled.start_date - self.start_date) < dtm.timedelta(seconds=1) assert abs(video_chat_scheduled.start_date - self.start_date) < dtm.timedelta(seconds=1)
def test_de_json_localization(self, tz_bot, bot, raw_bot): def test_de_json_localization(self, tz_bot, offline_bot, raw_bot):
json_dict = {"start_date": to_timestamp(self.start_date)} json_dict = {"start_date": to_timestamp(self.start_date)}
videochat_raw = VideoChatScheduled.de_json(json_dict, raw_bot) videochat_raw = VideoChatScheduled.de_json(json_dict, raw_bot)
videochat_bot = VideoChatScheduled.de_json(json_dict, bot) videochat_bot = VideoChatScheduled.de_json(json_dict, offline_bot)
videochat_tz = VideoChatScheduled.de_json(json_dict, tz_bot) videochat_tz = VideoChatScheduled.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable # comparing utcoffsets because comparing timezones is unpredicatable

View file

@ -46,9 +46,9 @@ class TestWebAppDataWithoutRequest(WebAppDataTestBase):
assert web_app_data_dict["data"] == self.data assert web_app_data_dict["data"] == self.data
assert web_app_data_dict["button_text"] == self.button_text assert web_app_data_dict["button_text"] == self.button_text
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = {"data": self.data, "button_text": self.button_text} json_dict = {"data": self.data, "button_text": self.button_text}
web_app_data = WebAppData.de_json(json_dict, bot) web_app_data = WebAppData.de_json(json_dict, offline_bot)
assert web_app_data.api_kwargs == {} assert web_app_data.api_kwargs == {}
assert web_app_data.data == self.data assert web_app_data.data == self.data

View file

@ -44,9 +44,9 @@ class TestWebAppInfoWithoutRequest(WebAppInfoTestBase):
assert isinstance(web_app_info_dict, dict) assert isinstance(web_app_info_dict, dict)
assert web_app_info_dict["url"] == self.url assert web_app_info_dict["url"] == self.url
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = {"url": self.url} json_dict = {"url": self.url}
web_app_info = WebAppInfo.de_json(json_dict, bot) web_app_info = WebAppInfo.de_json(json_dict, offline_bot)
assert web_app_info.api_kwargs == {} assert web_app_info.api_kwargs == {}
assert web_app_info.url == self.url assert web_app_info.url == self.url

View file

@ -72,7 +72,7 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase):
== self.last_synchronization_error_date == self.last_synchronization_error_date
) )
def test_de_json(self, bot): def test_de_json(self, offline_bot):
json_dict = { json_dict = {
"url": self.url, "url": self.url,
"has_custom_certificate": self.has_custom_certificate, "has_custom_certificate": self.has_custom_certificate,
@ -83,7 +83,7 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase):
"ip_address": self.ip_address, "ip_address": self.ip_address,
"last_synchronization_error_date": self.last_synchronization_error_date, "last_synchronization_error_date": self.last_synchronization_error_date,
} }
webhook_info = WebhookInfo.de_json(json_dict, bot) webhook_info = WebhookInfo.de_json(json_dict, offline_bot)
assert webhook_info.api_kwargs == {} assert webhook_info.api_kwargs == {}
assert webhook_info.url == self.url assert webhook_info.url == self.url
@ -99,10 +99,10 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase):
self.last_synchronization_error_date self.last_synchronization_error_date
) )
none = WebhookInfo.de_json(None, bot) none = WebhookInfo.de_json(None, offline_bot)
assert none is None assert none is None
def test_de_json_localization(self, bot, raw_bot, tz_bot): def test_de_json_localization(self, offline_bot, raw_bot, tz_bot):
json_dict = { json_dict = {
"url": self.url, "url": self.url,
"has_custom_certificate": self.has_custom_certificate, "has_custom_certificate": self.has_custom_certificate,
@ -113,7 +113,7 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase):
"ip_address": self.ip_address, "ip_address": self.ip_address,
"last_synchronization_error_date": self.last_synchronization_error_date, "last_synchronization_error_date": self.last_synchronization_error_date,
} }
webhook_info_bot = WebhookInfo.de_json(json_dict, bot) webhook_info_bot = WebhookInfo.de_json(json_dict, offline_bot)
webhook_info_raw = WebhookInfo.de_json(json_dict, raw_bot) webhook_info_raw = WebhookInfo.de_json(json_dict, raw_bot)
webhook_info_tz = WebhookInfo.de_json(json_dict, tz_bot) webhook_info_tz = WebhookInfo.de_json(json_dict, tz_bot)