diff --git a/tests/_files/test_animation.py b/tests/_files/test_animation.py index 493d9bfae..55c2076e2 100644 --- a/tests/_files/test_animation.py +++ b/tests/_files/test_animation.py @@ -84,7 +84,7 @@ class TestAnimationWithoutRequest(AnimationTestBase): assert animation.file_name.startswith("game.gif") == self.file_name.startswith("game.gif") assert isinstance(animation.thumbnail, PhotoSize) - def test_de_json(self, bot, animation): + def test_de_json(self, offline_bot, animation): json_dict = { "file_id": self.animation_file_id, "file_unique_id": self.animation_file_unique_id, @@ -96,7 +96,7 @@ class TestAnimationWithoutRequest(AnimationTestBase): "mime_type": self.mime_type, "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.file_id == self.animation_file_id assert animation.file_unique_id == self.animation_file_unique_id @@ -140,18 +140,22 @@ class TestAnimationWithoutRequest(AnimationTestBase): assert a != 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): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_animation(chat_id, animation_file, filename="custom_filename") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_animation( + chat_id, animation_file, filename="custom_filename" + ) @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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -167,18 +171,18 @@ class TestAnimationWithoutRequest(AnimationTestBase): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_animation(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_animation(chat_id, file, thumbnail=file) assert test_flag 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): return request_data.json_parameters["animation"] == animation.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_animation(animation=animation, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_animation(animation=animation, chat_id=chat_id) async def test_get_file_instance_method(self, monkeypatch, animation): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_audio.py b/tests/_files/test_audio.py index f6b76c1f0..ed0d74d4d 100644 --- a/tests/_files/test_audio.py +++ b/tests/_files/test_audio.py @@ -91,7 +91,7 @@ class TestAudioWithoutRequest(AudioTestBase): assert audio.thumbnail.width == self.thumb_width assert audio.thumbnail.height == self.thumb_height - def test_de_json(self, bot, audio): + def test_de_json(self, offline_bot, audio): json_dict = { "file_id": self.audio_file_id, "file_unique_id": self.audio_file_unique_id, @@ -103,7 +103,7 @@ class TestAudioWithoutRequest(AudioTestBase): "file_size": self.file_size, "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.file_id == self.audio_file_id @@ -147,25 +147,25 @@ class TestAudioWithoutRequest(AudioTestBase): assert a != 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): return request_data.json_parameters["audio"] == audio.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_audio(audio=audio, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + 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): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_audio(chat_id, audio_file, filename="custom_filename") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_audio(chat_id, audio_file, filename="custom_filename") @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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -179,11 +179,11 @@ class TestAudioWithoutRequest(AudioTestBase): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_audio(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_audio(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, audio): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_chatphoto.py b/tests/_files/test_chatphoto.py index 5deaae38f..5bbb6a8f7 100644 --- a/tests/_files/test_chatphoto.py +++ b/tests/_files/test_chatphoto.py @@ -66,14 +66,14 @@ class TestChatPhotoWithoutRequest(ChatPhotoTestBase): 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" - def test_de_json(self, bot, chat_photo): + def test_de_json(self, offline_bot, chat_photo): json_dict = { "small_file_id": self.chatphoto_small_file_id, "big_file_id": self.chatphoto_big_file_id, "small_file_unique_id": self.chatphoto_small_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.small_file_id == self.chatphoto_small_file_id assert chat_photo.big_file_id == self.chatphoto_big_file_id @@ -121,12 +121,14 @@ class TestChatPhotoWithoutRequest(ChatPhotoTestBase): assert a != 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): return request_data.parameters["photo"] == chat_photo.to_dict() - monkeypatch.setattr(bot.request, "post", make_assertion) - message = await bot.set_chat_photo(photo=chat_photo, chat_id=super_group_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + message = await offline_bot.set_chat_photo(photo=chat_photo, chat_id=super_group_id) assert message async def test_get_small_file_instance_method(self, monkeypatch, chat_photo): diff --git a/tests/_files/test_contact.py b/tests/_files/test_contact.py index cb5777eb4..0869d7ff3 100644 --- a/tests/_files/test_contact.py +++ b/tests/_files/test_contact.py @@ -52,22 +52,22 @@ class TestContactWithoutRequest(ContactTestBase): assert getattr(contact, attr, "err") != "err", f"got extra slot '{attr}'" 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} - contact = Contact.de_json(json_dict, bot) + contact = Contact.de_json(json_dict, offline_bot) assert contact.api_kwargs == {} assert contact.phone_number == self.phone_number assert contact.first_name == self.first_name - def test_de_json_all(self, bot): + def test_de_json_all(self, offline_bot): json_dict = { "phone_number": self.phone_number, "first_name": self.first_name, "last_name": self.last_name, "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.phone_number == self.phone_number @@ -104,20 +104,20 @@ class TestContactWithoutRequest(ContactTestBase): assert a != 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"): - 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"): - await bot.send_contact( + await offline_bot.send_contact( chat_id=chat_id, contact=contact, phone_number=contact.phone_number, 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): data = request_data.json_parameters phone = data["phone_number"] == contact.phone_number @@ -125,8 +125,8 @@ class TestContactWithoutRequest(ContactTestBase): last = data["last_name"] == contact.last_name return phone and first and last - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_contact(contact=contact, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_contact(contact=contact, chat_id=chat_id) @pytest.mark.parametrize( ("default_bot", "custom"), diff --git a/tests/_files/test_document.py b/tests/_files/test_document.py index 02f60ac46..90b6bdf11 100644 --- a/tests/_files/test_document.py +++ b/tests/_files/test_document.py @@ -83,7 +83,7 @@ class TestDocumentWithoutRequest(DocumentTestBase): assert document.thumbnail.width == self.thumb_width assert document.thumbnail.height == self.thumb_height - def test_de_json(self, bot, document): + def test_de_json(self, offline_bot, document): json_dict = { "file_id": self.document_file_id, "file_unique_id": self.document_file_unique_id, @@ -92,7 +92,7 @@ class TestDocumentWithoutRequest(DocumentTestBase): "mime_type": self.mime_type, "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.file_id == self.document_file_id @@ -128,13 +128,13 @@ class TestDocumentWithoutRequest(DocumentTestBase): assert a != 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): - 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]) 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): data = request_data.parameters @@ -143,9 +143,9 @@ class TestDocumentWithoutRequest(DocumentTestBase): ) 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, chat_id=chat_id, disable_content_type_detection=disable_content_type_detection, @@ -181,10 +181,10 @@ class TestDocumentWithoutRequest(DocumentTestBase): ) @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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -200,11 +200,11 @@ class TestDocumentWithoutRequest(DocumentTestBase): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_document(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_document(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, document): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_file.py b/tests/_files/test_file.py index ae9d92c04..70874d5fe 100644 --- a/tests/_files/test_file.py +++ b/tests/_files/test_file.py @@ -107,14 +107,14 @@ class TestFileWithoutRequest(FileTestBase): assert getattr(file, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "file_id": self.file_id, "file_unique_id": self.file_unique_id, "file_path": self.file_path, "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.file_id == self.file_id @@ -131,11 +131,11 @@ class TestFileWithoutRequest(FileTestBase): assert file_dict["file_path"] == file.file_path assert file_dict["file_size"] == file.file_size - def test_equality(self, bot): - a = File(self.file_id, self.file_unique_id, bot) - b = File("", self.file_unique_id, bot) + def test_equality(self, offline_bot): + a = File(self.file_id, self.file_unique_id, offline_bot) + b = File("", self.file_unique_id, offline_bot) 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) assert a == b @@ -223,7 +223,7 @@ class TestFileWithoutRequest(FileTestBase): 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): return data_file("image_encrypted.jpg").read_bytes() diff --git a/tests/_files/test_inputmedia.py b/tests/_files/test_inputmedia.py index ff398113a..6b54e4d19 100644 --- a/tests/_files/test_inputmedia.py +++ b/tests/_files/test_inputmedia.py @@ -655,7 +655,7 @@ def media_group_no_caption_only_parse_mode(photo, thumb): # noqa: F811 class TestSendMediaGroupWithoutRequest: async def test_send_media_group_throws_error_with_group_caption_and_individual_captions( self, - bot, + offline_bot, chat_id, media_group, media_group_no_caption_only_caption_entities, @@ -670,11 +670,11 @@ class TestSendMediaGroupWithoutRequest: ValueError, 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( self, - bot, + offline_bot, chat_id, photo_file, # noqa: F811 animation_file, # noqa: F811 @@ -690,7 +690,7 @@ class TestSendMediaGroupWithoutRequest: if result is True: raise Exception("Test was successful") - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) media = [ InputMediaAnimation(animation_file, filename="custom_filename"), @@ -700,10 +700,10 @@ class TestSendMediaGroupWithoutRequest: ] 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( - 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): nonlocal input_video @@ -715,13 +715,13 @@ class TestSendMediaGroupWithoutRequest: result = video_check and thumb_check 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) 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( - 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: str, url: str, request_data: Optional[RequestData] = None, *args, **kwargs @@ -734,10 +734,12 @@ class TestSendMediaGroupWithoutRequest: result = video_check and thumb_check 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) 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( ("default_bot", "custom"), diff --git a/tests/_files/test_location.py b/tests/_files/test_location.py index 72c6f7200..402f0ba7b 100644 --- a/tests/_files/test_location.py +++ b/tests/_files/test_location.py @@ -55,7 +55,7 @@ class TestLocationWithoutRequest(LocationTestBase): assert getattr(location, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "latitude": self.latitude, "longitude": self.longitude, @@ -64,7 +64,7 @@ class TestLocationWithoutRequest(LocationTestBase): "heading": self.heading, "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.latitude == self.latitude @@ -96,26 +96,28 @@ class TestLocationWithoutRequest(LocationTestBase): assert a != 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"): - 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"): - 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"): - 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"): - 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 ) # 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): data = request_data.json_parameters lat = data["latitude"] == str(location.latitude) @@ -127,8 +129,8 @@ class TestLocationWithoutRequest(LocationTestBase): live = data["live_period"] == "900" return lat and lon and id_ and ha and heading and prox_alert and live - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.edit_message_live_location( + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.edit_message_live_location( inline_message_id=1234, location=location, horizontal_accuracy=50, @@ -138,30 +140,30 @@ class TestLocationWithoutRequest(LocationTestBase): ) # 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): return request_data.json_parameters["inline_message_id"] == "1234" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.stop_message_live_location(inline_message_id=1234) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + 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): lat = request_data.json_parameters["latitude"] == str(location.latitude) lon = request_data.json_parameters["longitude"] == str(location.longitude) return lat and lon - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_location(location=location, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + 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): lat = request_data.json_parameters["latitude"] == str(location.latitude) lon = request_data.json_parameters["longitude"] == str(location.longitude) return lat and lon - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.edit_message_live_location(None, None, location=location) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.edit_message_live_location(None, None, location=location) @pytest.mark.parametrize( ("default_bot", "custom"), diff --git a/tests/_files/test_photo.py b/tests/_files/test_photo.py index 6ba9e46ac..919c3155b 100644 --- a/tests/_files/test_photo.py +++ b/tests/_files/test_photo.py @@ -105,7 +105,7 @@ class TestPhotoWithoutRequest(PhotoTestBase): # so far assert thumb.file_size in [1475, 1477] - def test_de_json(self, bot, photo): + def test_de_json(self, offline_bot, photo): json_dict = { "file_id": photo.file_id, "file_unique_id": photo.file_unique_id, @@ -113,7 +113,7 @@ class TestPhotoWithoutRequest(PhotoTestBase): "height": self.height, "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.file_id == photo.file_id @@ -160,22 +160,22 @@ class TestPhotoWithoutRequest(PhotoTestBase): assert a != 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): - 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): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_photo(chat_id, photo_file, filename="custom_filename") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_photo(chat_id, photo_file, filename="custom_filename") @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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -187,18 +187,18 @@ class TestPhotoWithoutRequest(PhotoTestBase): else: test_flag = isinstance(data.get("photo"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_photo(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_photo(chat_id, file) assert test_flag 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): return request_data.json_parameters["photo"] == photo.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_photo(photo=photo, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_photo(photo=photo, chat_id=chat_id) async def test_get_file_instance_method(self, monkeypatch, photo): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_sticker.py b/tests/_files/test_sticker.py index 3f374cc2e..3fa608e3a 100644 --- a/tests/_files/test_sticker.py +++ b/tests/_files/test_sticker.py @@ -165,7 +165,7 @@ class TestStickerWithoutRequest(StickerTestBase): assert sticker_dict["type"] == sticker.type 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 = { "file_id": self.sticker_file_id, "file_unique_id": self.sticker_file_unique_id, @@ -181,7 +181,7 @@ class TestStickerWithoutRequest(StickerTestBase): "custom_emoji_id": self.custom_emoji_id, "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.file_id == self.sticker_file_id @@ -284,22 +284,22 @@ class TestStickerWithoutRequest(StickerTestBase): assert a != 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): - 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): return request_data.json_parameters["sticker"] == sticker.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_sticker(sticker=sticker, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_sticker(sticker=sticker, chat_id=chat_id) @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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -311,11 +311,11 @@ class TestStickerWithoutRequest(StickerTestBase): else: test_flag = isinstance(data.get("sticker"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_sticker(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_sticker(chat_id, file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False @pytest.mark.parametrize( ("default_bot", "custom"), @@ -587,8 +587,8 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, sticker): - name = f"test_by_{bot.username}" + def test_de_json(self, offline_bot, sticker): + name = f"test_by_{offline_bot.username}" json_dict = { "name": name, "title": self.title, @@ -597,7 +597,7 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): "sticker_type": self.sticker_type, "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.title == self.title @@ -653,11 +653,11 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): @pytest.mark.parametrize("local_mode", [True, False]) 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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -670,24 +670,24 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): else isinstance(data.get("sticker"), InputFile) ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.upload_sticker_file( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.upload_sticker_file( chat_id, sticker=file, sticker_format=StickerFormat.STATIC ) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False @pytest.mark.parametrize("local_mode", [True, False]) async def test_create_new_sticker_set_local_files( self, monkeypatch, - bot, + offline_bot, chat_id, local_mode, ): - monkeypatch.setattr(bot, "_local_mode", 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 file = data_file("telegram.jpg") # 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 test_flag = data.get("stickers")[0].sticker == expected - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.create_new_sticker_set( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.create_new_sticker_set( chat_id, "name", "title", @@ -707,7 +707,9 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): ) 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): assert data["user_id"] == chat_id assert data["name"] == "name" @@ -715,8 +717,8 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): assert data["stickers"] == ["wow.png", "wow.tgs", "wow.webp"] assert data["needs_repainting"] is True - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.create_new_sticker_set( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.create_new_sticker_set( chat_id, "name", "title", @@ -725,9 +727,11 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): ) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_add_sticker_to_set_local_files(self, monkeypatch, bot, chat_id, local_mode): - monkeypatch.setattr(bot, "_local_mode", local_mode) - # For just test that the correct paths are passed as we have no local bot API set up + async def test_add_sticker_to_set_local_files( + self, monkeypatch, offline_bot, chat_id, 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 test_flag = False file = data_file("telegram.jpg") # 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 test_flag = data.get("sticker").sticker == expected - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.add_sticker_to_set( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.add_sticker_to_set( chat_id, "name", sticker=InputSticker(sticker=file, emoji_list=["this"], format="static"), @@ -748,11 +752,11 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): @pytest.mark.parametrize("local_mode", [True, False]) 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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -764,11 +768,13 @@ class TestStickerSetWithoutRequest(StickerSetTestBase): else: test_flag = isinstance(data.get("thumbnail"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.set_sticker_set_thumbnail("name", chat_id, thumbnail=file, format="static") + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.set_sticker_set_thumbnail( + "name", chat_id, thumbnail=file, format="static" + ) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, sticker): async def make_assertion(*_, **kwargs): @@ -1085,14 +1091,14 @@ class TestMaskPositionWithoutRequest(MaskPositionTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "point": self.point, "x_shift": self.x_shift, "y_shift": self.y_shift, "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.point == self.point diff --git a/tests/_files/test_venue.py b/tests/_files/test_venue.py index b78223bbf..31883591e 100644 --- a/tests/_files/test_venue.py +++ b/tests/_files/test_venue.py @@ -57,7 +57,7 @@ class TestVenueWithoutRequest(VenueTestBase): assert getattr(venue, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "location": self.location.to_dict(), "title": self.title, @@ -67,7 +67,7 @@ class TestVenueWithoutRequest(VenueTestBase): "google_place_id": self.google_place_id, "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.location == self.location @@ -110,13 +110,13 @@ class TestVenueWithoutRequest(VenueTestBase): assert a != 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"): - 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"): - await bot.send_venue( + await offline_bot.send_venue( chat_id=chat_id, latitude=1, longitude=1, @@ -125,7 +125,7 @@ class TestVenueWithoutRequest(VenueTestBase): 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): data = request_data.json_parameters return ( @@ -139,8 +139,8 @@ class TestVenueWithoutRequest(VenueTestBase): and data["google_place_type"] == self.google_place_type ) - monkeypatch.setattr(bot.request, "post", make_assertion) - message = await bot.send_venue(chat_id, venue=venue) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + message = await offline_bot.send_venue(chat_id, venue=venue) assert message @pytest.mark.parametrize( diff --git a/tests/_files/test_video.py b/tests/_files/test_video.py index 06666ea16..d4ace54e3 100644 --- a/tests/_files/test_video.py +++ b/tests/_files/test_video.py @@ -93,7 +93,7 @@ class TestVideoWithoutRequest(VideoTestBase): assert video.file_size == self.file_size assert video.mime_type == self.mime_type - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "file_id": self.video_file_id, "file_unique_id": self.video_file_unique_id, @@ -104,7 +104,7 @@ class TestVideoWithoutRequest(VideoTestBase): "file_size": self.file_size, "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.file_id == self.video_file_id @@ -149,30 +149,30 @@ class TestVideoWithoutRequest(VideoTestBase): assert a != 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): - 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): return request_data.json_parameters["video"] == video.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_video(chat_id, video=video) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + 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): 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]) - 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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -186,11 +186,11 @@ class TestVideoWithoutRequest(VideoTestBase): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_video(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_video(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, video): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_videonote.py b/tests/_files/test_videonote.py index b86355e44..d85de9fb4 100644 --- a/tests/_files/test_videonote.py +++ b/tests/_files/test_videonote.py @@ -85,7 +85,7 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase): assert video_note.duration == self.duration assert video_note.file_size == self.file_size - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "file_id": self.videonote_file_id, "file_unique_id": self.videonote_file_unique_id, @@ -93,7 +93,7 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase): "duration": self.duration, "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.file_id == self.videonote_file_id @@ -132,32 +132,36 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase): assert a != 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): - 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): return request_data.json_parameters["video_note"] == video_note.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_video_note(chat_id, video_note=video_note) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_video_note(chat_id, video_note=video_note) 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): 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]) - 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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -173,11 +177,11 @@ class TestVideoNoteWithoutRequest(VideoNoteTestBase): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_video_note(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_video_note(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, video_note): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_voice.py b/tests/_files/test_voice.py index 454db0aae..e32bb195c 100644 --- a/tests/_files/test_voice.py +++ b/tests/_files/test_voice.py @@ -78,7 +78,7 @@ class TestVoiceWithoutRequest(VoiceTestBase): assert voice.mime_type == self.mime_type assert voice.file_size == self.file_size - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "file_id": self.voice_file_id, "file_unique_id": self.voice_file_unique_id, @@ -86,7 +86,7 @@ class TestVoiceWithoutRequest(VoiceTestBase): "mime_type": self.mime_type, "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.file_id == self.voice_file_id @@ -125,30 +125,30 @@ class TestVoiceWithoutRequest(VoiceTestBase): assert a != 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): - 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): 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): return request_data.json_parameters["voice"] == voice.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_voice(chat_id, voice=voice) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_voice(chat_id, voice=voice) @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: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + 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 file = data_file("telegram.jpg") expected = file.as_uri() @@ -160,11 +160,11 @@ class TestVoiceWithoutRequest(VoiceTestBase): else: test_flag = isinstance(data.get("voice"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_voice(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_voice(chat_id, file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, voice): async def make_assertion(*_, **kwargs): diff --git a/tests/_games/test_game.py b/tests/_games/test_game.py index 23e0d5e9c..89a601321 100644 --- a/tests/_games/test_game.py +++ b/tests/_games/test_game.py @@ -55,20 +55,20 @@ class TestGameWithoutRequest(GameTestBase): assert getattr(game, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "title": self.title, "description": self.description, "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.title == self.title assert game.description == self.description assert game.photo == tuple(self.photo) - def test_de_json_all(self, bot): + def test_de_json_all(self, offline_bot): json_dict = { "title": self.title, "description": self.description, @@ -77,7 +77,7 @@ class TestGameWithoutRequest(GameTestBase): "text_entities": [self.text_entities[0].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.title == self.title diff --git a/tests/_games/test_gamehighscore.py b/tests/_games/test_gamehighscore.py index fc76867b4..c07488c80 100644 --- a/tests/_games/test_gamehighscore.py +++ b/tests/_games/test_gamehighscore.py @@ -42,20 +42,20 @@ class TestGameHighScoreWithoutRequest(GameHighScoreTestBase): 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" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "position": self.position, "user": self.user.to_dict(), "score": self.score, } - highscore = GameHighScore.de_json(json_dict, bot) + highscore = GameHighScore.de_json(json_dict, offline_bot) assert highscore.api_kwargs == {} assert highscore.position == self.position assert highscore.user == self.user 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): game_highscore_dict = game_highscore.to_dict() diff --git a/tests/_inline/test_inlinekeyboardbutton.py b/tests/_inline/test_inlinekeyboardbutton.py index 2569a8902..6e406f3ec 100644 --- a/tests/_inline/test_inlinekeyboardbutton.py +++ b/tests/_inline/test_inlinekeyboardbutton.py @@ -116,7 +116,7 @@ class TestInlineKeyboardButtonWithoutRequest(InlineKeyboardButtonTestBase): == 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 = { "text": self.text, "url": self.url, @@ -150,7 +150,7 @@ class TestInlineKeyboardButtonWithoutRequest(InlineKeyboardButtonTestBase): == self.switch_inline_query_chosen_chat ) - none = InlineKeyboardButton.de_json({}, bot) + none = InlineKeyboardButton.de_json({}, offline_bot) assert none is None def test_equality(self): diff --git a/tests/_inline/test_inlinekeyboardmarkup.py b/tests/_inline/test_inlinekeyboardmarkup.py index 2f5bd2a5a..461379436 100644 --- a/tests/_inline/test_inlinekeyboardmarkup.py +++ b/tests/_inline/test_inlinekeyboardmarkup.py @@ -192,7 +192,9 @@ class TestInlineKeyboardMarkupWithoutRequest(InlineKeyboardMarkupTestBase): with pytest.raises(ValueError, match="should be a sequence of sequences"): 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( url, 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].switch_inline_query_current_chat = "" - monkeypatch.setattr(bot, "_send_message", make_assertion) - await bot.send_message(123, "test", reply_markup=inline_keyboard_markup) + monkeypatch.setattr(offline_bot, "_send_message", make_assertion) + await offline_bot.send_message(123, "test", reply_markup=inline_keyboard_markup) class TestInlineKeyborardMarkupWithRequest(InlineKeyboardMarkupTestBase): diff --git a/tests/_inline/test_inlinequery.py b/tests/_inline/test_inlinequery.py index 4d2e73ffb..7ff22c445 100644 --- a/tests/_inline/test_inlinequery.py +++ b/tests/_inline/test_inlinequery.py @@ -55,7 +55,7 @@ class TestInlineQueryWithoutRequest(InlineQueryTestBase): 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" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "from": self.from_user.to_dict(), @@ -63,7 +63,7 @@ class TestInlineQueryWithoutRequest(InlineQueryTestBase): "offset": self.offset, "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.id == self.id_ diff --git a/tests/_inline/test_inputinvoicemessagecontent.py b/tests/_inline/test_inputinvoicemessagecontent.py index 17bfad013..4e35e9f6f 100644 --- a/tests/_inline/test_inputinvoicemessagecontent.py +++ b/tests/_inline/test_inputinvoicemessagecontent.py @@ -203,8 +203,8 @@ class TestInputInvoiceMessageContentWithoutRequest(InputInvoiceMessageContentTes == input_invoice_message_content.is_flexible ) - def test_de_json(self, bot): - assert InputInvoiceMessageContent.de_json({}, bot=bot) is None + def test_de_json(self, offline_bot): + assert InputInvoiceMessageContent.de_json({}, bot=offline_bot) is None json_dict = { "title": self.title, @@ -229,7 +229,9 @@ class TestInputInvoiceMessageContentWithoutRequest(InputInvoiceMessageContentTes "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.title == self.title diff --git a/tests/_passport/test_no_passport.py b/tests/_passport/test_no_passport.py index 8b1af252c..ff3ce0a43 100644 --- a/tests/_passport/test_no_passport.py +++ b/tests/_passport/test_no_passport.py @@ -28,7 +28,7 @@ with the TEST_WITH_OPT_DEPS environment variable set to False in addition to the """ import pytest -from telegram import _bot as bot +import telegram from telegram._passport import credentials from tests.auxil.envvars import TEST_WITH_OPT_DEPS @@ -39,7 +39,7 @@ from tests.auxil.envvars import TEST_WITH_OPT_DEPS class TestNoPassportWithoutRequest: def test_bot_init(self, bot_info): 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): with pytest.raises(RuntimeError, match="passport"): diff --git a/tests/_passport/test_passport.py b/tests/_passport/test_passport.py index 9303ae7eb..b094f808f 100644 --- a/tests/_passport/test_passport.py +++ b/tests/_passport/test_passport.py @@ -390,8 +390,8 @@ class TestPassportWithoutRequest(PassportTestBase): assert email.type == "email" assert email.email == "fb3e3i47zt@dispostable.com" - def test_de_json_and_to_dict(self, bot): - passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot) + def test_de_json_and_to_dict(self, offline_bot): + passport_data = PassportData.de_json(RAW_PASSPORT_DATA, offline_bot) assert passport_data.api_kwargs == {} assert passport_data.to_dict() == RAW_PASSPORT_DATA @@ -414,14 +414,14 @@ class TestPassportWithoutRequest(PassportTestBase): assert a != 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): - 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"): - 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() # Copy credentials from other types to all types so we can decrypt everything @@ -446,46 +446,46 @@ class TestPassportWithoutRequest(PassportTestBase): # Replaced below "credentials": {"data": "data", "hash": "hash", "secret": "secret"}, }, - bot=bot, + bot=offline_bot, ) 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 isinstance(new, PassportData) assert new.decrypted_data - async def test_passport_data_okay_with_non_crypto_bot(self, bot): - async with make_bot(token=bot.token) as b: + async def test_passport_data_okay_with_non_crypto_bot(self, offline_bot): + async with make_bot(token=offline_bot.token) as 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["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): assert passport_data.decrypted_data - async def test_wrong_key(self, bot): + async def test_wrong_key(self, offline_bot): short_key = ( 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" 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) with pytest.raises(PassportDecryptionError): 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) with pytest.raises(PassportDecryptionError): assert passport_data.decrypted_data 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 - # when coming from this bot, so we monkeypatch the call, to make sure that Bot.get_file + # The files are not coming from our test offline_bot, therefore the file id is invalid/wrong + # when coming from this offline_bot, so we monkeypatch the call, to make sure that Bot.get_file # at least gets called # TODO: Actually download a passport file in a test 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.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): data = request_data.parameters return ( @@ -514,8 +516,8 @@ class TestPassportWithoutRequest(PassportTestBase): == passport_data.decrypted_credentials.secure_data.driver_license.data.data_hash ) - monkeypatch.setattr(bot.request, "post", make_assertion) - message = await bot.set_passport_data_errors( + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + message = await offline_bot.set_passport_data_errors( chat_id, [ PassportElementErrorSelfie( diff --git a/tests/_payment/test_invoice.py b/tests/_payment/test_invoice.py index 2293fe587..585f4fd3e 100644 --- a/tests/_payment/test_invoice.py +++ b/tests/_payment/test_invoice.py @@ -58,7 +58,7 @@ class TestInvoiceWithoutRequest(InvoiceTestBase): assert getattr(invoice, attr, "err") != "err", f"got extra slot '{attr}'" 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( { "title": self.title, @@ -67,7 +67,7 @@ class TestInvoiceWithoutRequest(InvoiceTestBase): "currency": self.currency, "total_amount": self.total_amount, }, - bot, + offline_bot, ) assert invoice_json.api_kwargs == {} @@ -87,15 +87,15 @@ class TestInvoiceWithoutRequest(InvoiceTestBase): assert invoice_dict["currency"] == invoice.currency 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 # parameters correctly because #2526 went unnoticed for 3 years … async def make_assertion(*args, **_): kwargs = args[1] return all(kwargs[key] == key for key in kwargs) - monkeypatch.setattr(bot, "_send_message", make_assertion) - assert await bot.send_invoice( + monkeypatch.setattr(offline_bot, "_send_message", make_assertion) + assert await offline_bot.send_invoice( chat_id="chat_id", title="title", description="description", @@ -122,13 +122,13 @@ class TestInvoiceWithoutRequest(InvoiceTestBase): 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, **_): kwargs = args[1] return all(kwargs[i] == i for i in kwargs) - monkeypatch.setattr(bot, "_post", make_assertion) - assert await bot.create_invoice_link( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + assert await offline_bot.create_invoice_link( title="title", description="description", payload="payload", @@ -151,13 +151,15 @@ class TestInvoiceWithoutRequest(InvoiceTestBase): 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): 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, self.title, self.description, diff --git a/tests/_payment/test_orderinfo.py b/tests/_payment/test_orderinfo.py index 8e27ed343..4f6317222 100644 --- a/tests/_payment/test_orderinfo.py +++ b/tests/_payment/test_orderinfo.py @@ -45,14 +45,14 @@ class TestOrderInfoWithoutRequest(OrderInfoTestBase): 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" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "name": self.name, "phone_number": self.phone_number, "email": self.email, "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.name == self.name diff --git a/tests/_payment/test_precheckoutquery.py b/tests/_payment/test_precheckoutquery.py index aaca70407..e61adbcf9 100644 --- a/tests/_payment/test_precheckoutquery.py +++ b/tests/_payment/test_precheckoutquery.py @@ -60,7 +60,7 @@ class TestPreCheckoutQueryWithoutRequest(PreCheckoutQueryTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "id": self.id_, "invoice_payload": self.invoice_payload, @@ -70,10 +70,10 @@ class TestPreCheckoutQueryWithoutRequest(PreCheckoutQueryTestBase): "from": self.from_user.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.get_bot() is bot + assert pre_checkout_query.get_bot() is offline_bot assert pre_checkout_query.id == self.id_ assert pre_checkout_query.invoice_payload == self.invoice_payload assert pre_checkout_query.shipping_option_id == self.shipping_option_id diff --git a/tests/_payment/test_refundedpayment.py b/tests/_payment/test_refundedpayment.py index 8ea4d1a50..32581f785 100644 --- a/tests/_payment/test_refundedpayment.py +++ b/tests/_payment/test_refundedpayment.py @@ -48,7 +48,7 @@ class TestRefundedPaymentWithoutRequest(RefundedPaymentTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "invoice_payload": self.invoice_payload, "currency": self.currency, @@ -56,7 +56,7 @@ class TestRefundedPaymentWithoutRequest(RefundedPaymentTestBase): "telegram_payment_charge_id": self.telegram_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.invoice_payload == self.invoice_payload diff --git a/tests/_payment/test_shippingaddress.py b/tests/_payment/test_shippingaddress.py index 41fbeba5a..371c8d2fc 100644 --- a/tests/_payment/test_shippingaddress.py +++ b/tests/_payment/test_shippingaddress.py @@ -50,7 +50,7 @@ class TestShippingAddressWithoutRequest(ShippingAddressTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "country_code": self.country_code, "state": self.state, @@ -59,7 +59,7 @@ class TestShippingAddressWithoutRequest(ShippingAddressTestBase): "street_line2": self.street_line2, "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.country_code == self.country_code diff --git a/tests/_payment/test_shippingquery.py b/tests/_payment/test_shippingquery.py index 4821cbae9..da99c1fd1 100644 --- a/tests/_payment/test_shippingquery.py +++ b/tests/_payment/test_shippingquery.py @@ -54,21 +54,21 @@ class TestShippingQueryWithoutRequest(ShippingQueryTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "id": self.id_, "invoice_payload": self.invoice_payload, "from": self.from_user.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.id == self.id_ assert shipping_query.invoice_payload == self.invoice_payload assert shipping_query.from_user == self.from_user 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): shipping_query_dict = shipping_query.to_dict() diff --git a/tests/_payment/test_successfulpayment.py b/tests/_payment/test_successfulpayment.py index c4562d0a8..2b4cf0918 100644 --- a/tests/_payment/test_successfulpayment.py +++ b/tests/_payment/test_successfulpayment.py @@ -52,7 +52,7 @@ class TestSuccessfulPaymentWithoutRequest(SuccessfulPaymentTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "invoice_payload": self.invoice_payload, "shipping_option_id": self.shipping_option_id, @@ -62,7 +62,7 @@ class TestSuccessfulPaymentWithoutRequest(SuccessfulPaymentTestBase): "telegram_payment_charge_id": self.telegram_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.invoice_payload == self.invoice_payload diff --git a/tests/conftest.py b/tests/conftest.py index e8ef01cab..b637f8957 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -39,9 +39,9 @@ from telegram import ( ) from telegram.ext import Defaults 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.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.networking import NonchalantHttpxRequest 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) +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 # session. See https://github.com/pytest-dev/pytest-asyncio/issues/68 for more details. @pytest.fixture(scope="session") diff --git a/tests/request/test_request.py b/tests/request/test_request.py index 2bbfcf52d..bd186c2ef 100644 --- a/tests/request/test_request.py +++ b/tests/request/test_request.py @@ -84,7 +84,7 @@ async def httpx_request(): TEST_WITH_OPT_DEPS, reason="Only relevant if the optional dependency is not installed" ) 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\]"): HTTPXRequest(proxy="socks5://foo") 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["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): with pytest.raises(ValueError, match="`http_version` must be either"): 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): await httpx_request.shutdown() 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") 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): """The pool logic is buried rather deeply in httpxcore, so we make actual requests here instead of mocking""" diff --git a/tests/test_birthdate.py b/tests/test_birthdate.py index c22ebd9af..11cb96a18 100644 --- a/tests/test_birthdate.py +++ b/tests/test_birthdate.py @@ -48,9 +48,9 @@ class TestBirthdateWithoutRequest(BirthdateTestBase): assert bd_dict["month"] == self.month 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} - bd = Birthdate.de_json(json_dict, bot) + bd = Birthdate.de_json(json_dict, offline_bot) assert isinstance(bd, Birthdate) assert bd.day == self.day assert bd.month == self.month diff --git a/tests/test_bot.py b/tests/test_bot.py index 705b14c6d..fa723093f 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -99,7 +99,7 @@ from tests.auxil.bot_method_checks import check_defaults_handling from tests.auxil.ci_bots import FALLBACKS from tests.auxil.envvars import GITHUB_ACTION, TEST_WITH_OPT_DEPS from tests.auxil.files import data_file -from tests.auxil.networking import NonchalantHttpxRequest, expect_bad_request +from tests.auxil.networking import OfflineRequest, expect_bad_request from tests.auxil.pytest_classes import PytestBot, PytestExtBot, make_bot from tests.auxil.slots import mro_slots @@ -224,8 +224,8 @@ class TestBotWithoutRequest: self.test_flag = None @pytest.mark.parametrize("bot_class", [Bot, ExtBot]) - def test_slot_behaviour(self, bot_class, bot): - inst = bot_class(bot.token) + def test_slot_behaviour(self, bot_class, offline_bot): + inst = bot_class(offline_bot.token) for attr in inst.__slots__: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" @@ -235,27 +235,27 @@ class TestBotWithoutRequest: Bot("") async def test_repr(self): - bot = Bot(token="some_token", base_file_url="") - assert repr(bot) == "Bot[token=some_token]" + offline_bot = Bot(token="some_token", base_file_url="") + assert repr(offline_bot) == "Bot[token=some_token]" - async def test_to_dict(self, bot): - to_dict_bot = bot.to_dict() + async def test_to_dict(self, offline_bot): + to_dict_bot = offline_bot.to_dict() assert isinstance(to_dict_bot, dict) - assert to_dict_bot["id"] == bot.id - assert to_dict_bot["username"] == bot.username - assert to_dict_bot["first_name"] == bot.first_name - if bot.last_name: - assert to_dict_bot["last_name"] == bot.last_name + assert to_dict_bot["id"] == offline_bot.id + assert to_dict_bot["username"] == offline_bot.username + assert to_dict_bot["first_name"] == offline_bot.first_name + if offline_bot.last_name: + assert to_dict_bot["last_name"] == offline_bot.last_name - async def test_initialize_and_shutdown(self, bot: PytestExtBot, monkeypatch): + async def test_initialize_and_shutdown(self, offline_bot: PytestExtBot, monkeypatch): async def initialize(*args, **kwargs): self.test_flag = ["initialize"] async def stop(*args, **kwargs): self.test_flag.append("stop") - temp_bot = PytestBot(token=bot.token, request=NonchalantHttpxRequest()) + temp_bot = PytestBot(token=offline_bot.token, request=OfflineRequest()) orig_stop = temp_bot.request.shutdown try: @@ -263,14 +263,14 @@ class TestBotWithoutRequest: monkeypatch.setattr(temp_bot.request, "shutdown", stop) await temp_bot.initialize() assert self.test_flag == ["initialize"] - assert temp_bot.bot == bot.bot + assert temp_bot.bot == offline_bot.bot await temp_bot.shutdown() assert self.test_flag == ["initialize", "stop"] finally: await orig_stop() - async def test_multiple_inits_and_shutdowns(self, bot, monkeypatch): + async def test_multiple_inits_and_shutdowns(self, offline_bot, monkeypatch): self.received = defaultdict(int) async def initialize(*args, **kwargs): @@ -282,7 +282,7 @@ class TestBotWithoutRequest: monkeypatch.setattr(HTTPXRequest, "initialize", initialize) monkeypatch.setattr(HTTPXRequest, "shutdown", shutdown) - test_bot = PytestBot(bot.token) + test_bot = PytestBot(offline_bot.token) await test_bot.initialize() await test_bot.initialize() await test_bot.initialize() @@ -290,37 +290,37 @@ class TestBotWithoutRequest: await test_bot.shutdown() await test_bot.shutdown() - # 2 instead of 1 since we have to request objects for each bot + # 2 instead of 1 since we have to request objects for each offline_bot assert self.received["init"] == 2 assert self.received["shutdown"] == 2 - async def test_context_manager(self, monkeypatch, bot): + async def test_context_manager(self, monkeypatch, offline_bot): async def initialize(): self.test_flag = ["initialize"] async def shutdown(*args): self.test_flag.append("stop") - monkeypatch.setattr(bot, "initialize", initialize) - monkeypatch.setattr(bot, "shutdown", shutdown) + monkeypatch.setattr(offline_bot, "initialize", initialize) + monkeypatch.setattr(offline_bot, "shutdown", shutdown) - async with bot: + async with offline_bot: pass assert self.test_flag == ["initialize", "stop"] - async def test_context_manager_exception_on_init(self, monkeypatch, bot): + async def test_context_manager_exception_on_init(self, monkeypatch, offline_bot): async def initialize(): raise RuntimeError("initialize") async def shutdown(): self.test_flag = "stop" - monkeypatch.setattr(bot, "initialize", initialize) - monkeypatch.setattr(bot, "shutdown", shutdown) + monkeypatch.setattr(offline_bot, "initialize", initialize) + monkeypatch.setattr(offline_bot, "shutdown", shutdown) with pytest.raises(RuntimeError, match="initialize"): - async with bot: + async with offline_bot: pass assert self.test_flag == "stop" @@ -362,43 +362,43 @@ class TestBotWithoutRequest: "link", ], ) - async def test_get_me_and_properties_not_initialized(self, bot: Bot, attribute): - bot = Bot(token=bot.token) + async def test_get_me_and_properties_not_initialized(self, offline_bot: Bot, attribute): + offline_bot = Bot(token=offline_bot.token) try: with pytest.raises(RuntimeError, match="not properly initialized"): - bot[attribute] + offline_bot[attribute] finally: - await bot.shutdown() + await offline_bot.shutdown() - async def test_get_me_and_properties(self, bot): - get_me_bot = await ExtBot(bot.token).get_me() + async def test_get_me_and_properties(self, offline_bot): + get_me_bot = await ExtBot(offline_bot.token).get_me() assert isinstance(get_me_bot, User) - assert get_me_bot.id == bot.id - assert get_me_bot.username == bot.username - assert get_me_bot.first_name == bot.first_name - assert get_me_bot.last_name == bot.last_name - assert get_me_bot.name == bot.name - assert get_me_bot.can_join_groups == bot.can_join_groups - assert get_me_bot.can_read_all_group_messages == bot.can_read_all_group_messages - assert get_me_bot.supports_inline_queries == bot.supports_inline_queries - assert f"https://t.me/{get_me_bot.username}" == bot.link + assert get_me_bot.id == offline_bot.id + assert get_me_bot.username == offline_bot.username + assert get_me_bot.first_name == offline_bot.first_name + assert get_me_bot.last_name == offline_bot.last_name + assert get_me_bot.name == offline_bot.name + assert get_me_bot.can_join_groups == offline_bot.can_join_groups + assert get_me_bot.can_read_all_group_messages == offline_bot.can_read_all_group_messages + assert get_me_bot.supports_inline_queries == offline_bot.supports_inline_queries + assert f"https://t.me/{get_me_bot.username}" == offline_bot.link - def test_bot_pickling_error(self, bot): + def test_bot_pickling_error(self, offline_bot): with pytest.raises(pickle.PicklingError, match="Bot objects cannot be pickled"): - pickle.dumps(bot) + pickle.dumps(offline_bot) - def test_bot_deepcopy_error(self, bot): + def test_bot_deepcopy_error(self, offline_bot): with pytest.raises(TypeError, match="Bot objects cannot be deepcopied"): - copy.deepcopy(bot) + copy.deepcopy(offline_bot) @pytest.mark.parametrize( ("cls", "logger_name"), [(Bot, "telegram.Bot"), (ExtBot, "telegram.ext.ExtBot")] ) - async def test_bot_method_logging(self, bot: PytestExtBot, cls, logger_name, caplog): + async def test_bot_method_logging(self, offline_bot: PytestExtBot, cls, logger_name, caplog): # Second argument makes sure that we ignore logs from e.g. httpx with caplog.at_level(logging.DEBUG, logger="telegram"): - await cls(bot.token).get_me() + await cls(offline_bot.token).get_me() # Only for stabilizing this test- if len(caplog.records) == 4: for idx, record in enumerate(caplog.records): @@ -430,13 +430,13 @@ class TestBotWithoutRequest: @bot_methods(include_do_api_request=True) def test_coroutine_functions(self, bot_class, bot_method_name, bot_method): - """Check that all bot methods are defined as async def ...""" + """Check that all offline_bot methods are defined as async def ...""" meth = getattr(bot_method, "__wrapped__", bot_method) # to unwrap the @_log decorator assert inspect.iscoroutinefunction(meth), f"{bot_method_name} must be a coroutine function" @bot_methods(include_do_api_request=True) def test_api_kwargs_and_timeouts_present(self, bot_class, bot_method_name, bot_method): - """Check that all bot methods have `api_kwargs` and timeout params.""" + """Check that all offline_bot methods have `api_kwargs` and timeout params.""" param_names = inspect.signature(bot_method).parameters.keys() params = ("pool_timeout", "read_timeout", "connect_timeout", "write_timeout", "api_kwargs") @@ -453,11 +453,12 @@ class TestBotWithoutRequest: bot_class, bot_method_name: str, bot_method, - bot: PytestExtBot, + offline_bot: PytestExtBot, raw_bot: PytestBot, ): """ - Here we check that the bot methods handle tg.ext.Defaults correctly. This has two parts: + Here we check that the offline_bot methods handle tg.ext.Defaults correctly. This has two + parts: 1. Check that ExtBot actually inserts the defaults values correctly 2. Check that tg.Bot just replaces `DefaultValue(obj)` with `obj`, i.e. that it doesn't @@ -466,8 +467,8 @@ class TestBotWithoutRequest: As for most defaults, we can't really check the effect, we just check if we're passing the correct kwargs to - Request.post. As bot method tests a scattered across the different test files, we do - this here in one place. + Request.post. As offline_bot method tests a scattered across the different test files, we + do this here in one place. The same test is also run for all the shortcuts (Message.reply_text) etc in the corresponding tests. @@ -477,12 +478,14 @@ class TestBotWithoutRequest: """ # Mocking get_me within check_defaults_handling messes with the cached values like # Bot.{bot, username, id, …}` unless we return the expected User object. - return_value = bot.bot if bot_method_name.lower().replace("_", "") == "getme" else None + return_value = ( + offline_bot.bot if bot_method_name.lower().replace("_", "") == "getme" else None + ) # Check that ExtBot does the right thing - bot_method = getattr(bot, bot_method_name) + bot_method = getattr(offline_bot, bot_method_name) raw_bot_method = getattr(raw_bot, bot_method_name) - assert await check_defaults_handling(bot_method, bot, return_value=return_value) + assert await check_defaults_handling(bot_method, offline_bot, return_value=return_value) assert await check_defaults_handling(raw_bot_method, raw_bot, return_value=return_value) @pytest.mark.parametrize( @@ -523,19 +526,19 @@ class TestBotWithoutRequest: param.kind == ext_signature.parameters[param_name].kind ), f"Wrong parameter kind for parameter {param_name} of method {name}" - async def test_unknown_kwargs(self, bot, monkeypatch): + async def test_unknown_kwargs(self, offline_bot, monkeypatch): async def post(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters if not all([data["unknown_kwarg_1"] == "7", data["unknown_kwarg_2"] == "5"]): pytest.fail("got wrong parameters") return True - monkeypatch.setattr(bot.request, "post", post) - await bot.send_message( + monkeypatch.setattr(offline_bot.request, "post", post) + await offline_bot.send_message( 123, "text", api_kwargs={"unknown_kwarg_1": 7, "unknown_kwarg_2": 5} ) - async def test_get_updates_deserialization_error(self, bot, monkeypatch, caplog): + async def test_get_updates_deserialization_error(self, offline_bot, monkeypatch, caplog): async def faulty_do_request(*args, **kwargs): return ( HTTPStatus.OK, @@ -544,10 +547,10 @@ class TestBotWithoutRequest: monkeypatch.setattr(HTTPXRequest, "do_request", faulty_do_request) - bot = PytestExtBot(get_updates_request=HTTPXRequest(), token=bot.token) + offline_bot = PytestExtBot(get_updates_request=HTTPXRequest(), token=offline_bot.token) with caplog.at_level(logging.CRITICAL), pytest.raises(AttributeError): - await bot.get_updates() + await offline_bot.get_updates() assert len(caplog.records) == 1 assert caplog.records[0].name == "telegram.ext.ExtBot" @@ -558,7 +561,7 @@ class TestBotWithoutRequest: ) assert caplog.records[0].exc_info[0] is AttributeError - async def test_answer_web_app_query(self, bot, raw_bot, monkeypatch): + async def test_answer_web_app_query(self, offline_bot, raw_bot, monkeypatch): params = False # For now just test that our internals pass the correct data @@ -583,9 +586,9 @@ class TestBotWithoutRequest: result = InlineQueryResultArticle("1", "title", InputTextMessageContent("text")) copied_result = copy.copy(result) - ext_bot = bot + ext_bot = offline_bot for bot_type in (ext_bot, raw_bot): - # We need to test 1) below both the bot and raw_bot and setting this up with + # We need to test 1) below both the offline_bot and raw_bot and setting this up with # pytest.parametrize appears to be difficult ... monkeypatch.setattr(bot_type.request, "post", make_assertion) web_app_msg = await bot_type.answer_web_app_query("12345", result) @@ -679,7 +682,7 @@ class TestBotWithoutRequest: async def test_answer_web_app_query_defaults( self, default_bot, ilq_result, expected_params, monkeypatch ): - bot = default_bot + offline_bot = default_bot params = False # For now just test that our internals pass the correct data @@ -689,13 +692,13 @@ class TestBotWithoutRequest: params = request_data.parameters == expected_params return SentWebAppMessage("321").to_dict() - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) # We test different result types more thoroughly for answer_inline_query, so we just # use the one type here copied_result = copy.copy(ilq_result) - web_app_msg = await bot.answer_web_app_query("12345", ilq_result) + web_app_msg = await offline_bot.answer_web_app_query("12345", ilq_result) assert params, "something went wrong with passing arguments to the request" assert isinstance(web_app_msg, SentWebAppMessage) assert web_app_msg.inline_message_id == "321" @@ -709,7 +712,7 @@ class TestBotWithoutRequest: # TODO: Needs improvement. We need incoming inline query to test answer. @pytest.mark.parametrize("button_type", ["start", "web_app"]) - async def test_answer_inline_query(self, monkeypatch, bot, raw_bot, button_type): + async def test_answer_inline_query(self, monkeypatch, offline_bot, raw_bot, button_type): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): expected = { @@ -785,9 +788,9 @@ class TestBotWithoutRequest: button = None copied_results = copy.copy(results) - ext_bot = bot + ext_bot = offline_bot for bot_type in (ext_bot, raw_bot): - # We need to test 1) below both the bot and raw_bot and setting this up with + # We need to test 1) below both the offline_bot and raw_bot and setting this up with # pytest.parametrize appears to be difficult ... monkeypatch.setattr(bot_type.request, "post", make_assertion) assert await bot_type.answer_inline_query( @@ -817,7 +820,7 @@ class TestBotWithoutRequest: monkeypatch.delattr(bot_type.request, "post") - async def test_answer_inline_query_no_default_parse_mode(self, monkeypatch, bot): + async def test_answer_inline_query_no_default_parse_mode(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { "cache_time": 300, @@ -853,7 +856,7 @@ class TestBotWithoutRequest: "is_personal": True, } - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) results = [ InlineQueryResultArticle("11", "first", InputTextMessageContent("first")), InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")), @@ -871,7 +874,7 @@ class TestBotWithoutRequest: ] copied_results = copy.copy(results) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=results, cache_time=300, @@ -1003,7 +1006,7 @@ class TestBotWithoutRequest: async def test_answer_inline_query_current_offset_1( self, monkeypatch, - bot, + offline_bot, inline_results, current_offset, num_results, @@ -1019,13 +1022,15 @@ class TestBotWithoutRequest: next_offset_matches = data["next_offset"] == str(expected_next_offset) return length_matches and ids_match and next_offset_matches - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=inline_results, current_offset=current_offset ) - async def test_answer_inline_query_current_offset_2(self, monkeypatch, bot, inline_results): + async def test_answer_inline_query_current_offset_2( + self, monkeypatch, offline_bot, inline_results + ): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters @@ -1035,9 +1040,11 @@ class TestBotWithoutRequest: next_offset_matches = data["next_offset"] == "1" return length_matches and ids_match and next_offset_matches - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query(1234, results=inline_results, current_offset=0) + assert await offline_bot.answer_inline_query( + 1234, results=inline_results, current_offset=0 + ) inline_results = inline_results[:30] @@ -1049,11 +1056,13 @@ class TestBotWithoutRequest: next_offset_matches = not data["next_offset"] return length_matches and ids_match and next_offset_matches - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query(1234, results=inline_results, current_offset=0) + assert await offline_bot.answer_inline_query( + 1234, results=inline_results, current_offset=0 + ) - async def test_answer_inline_query_current_offset_callback(self, monkeypatch, bot): + async def test_answer_inline_query_current_offset_callback(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters @@ -1063,9 +1072,9 @@ class TestBotWithoutRequest: next_offset = data["next_offset"] == "2" return length and ids and next_offset - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=inline_results_callback, current_offset=1 ) @@ -1076,61 +1085,63 @@ class TestBotWithoutRequest: next_offset = not data["next_offset"] return length and next_offset - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=inline_results_callback, current_offset=6 ) - async def test_send_edit_message_mutually_exclusive_link_preview(self, bot, chat_id): + async def test_send_edit_message_mutually_exclusive_link_preview(self, offline_bot, chat_id): """Test that link_preview is mutually exclusive with disable_web_page_preview.""" with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"): - await bot.send_message( + await offline_bot.send_message( chat_id, "text", disable_web_page_preview=True, link_preview_options="something" ) with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"): - await bot.edit_message_text( + await offline_bot.edit_message_text( "text", chat_id, 1, disable_web_page_preview=True, link_preview_options="something" ) - async def test_rtm_aswr_mutually_exclusive_reply_parameters(self, bot, chat_id): + async def test_rtm_aswr_mutually_exclusive_reply_parameters(self, offline_bot, chat_id): """Test that reply_to_message_id and allow_sending_without_reply are mutually exclusive with reply_parameters.""" with pytest.raises(ValueError, match="`reply_to_message_id` and"): - await bot.send_message(chat_id, "text", reply_to_message_id=1, reply_parameters=True) + await offline_bot.send_message( + chat_id, "text", reply_to_message_id=1, reply_parameters=True + ) with pytest.raises(ValueError, match="`allow_sending_without_reply` and"): - await bot.send_message( + await offline_bot.send_message( chat_id, "text", allow_sending_without_reply=True, reply_parameters=True ) # Test with copy message with pytest.raises(ValueError, match="`reply_to_message_id` and"): - await bot.copy_message( + await offline_bot.copy_message( chat_id, chat_id, 1, reply_to_message_id=1, reply_parameters=True ) with pytest.raises(ValueError, match="`allow_sending_without_reply` and"): - await bot.copy_message( + await offline_bot.copy_message( chat_id, chat_id, 1, allow_sending_without_reply=True, reply_parameters=True ) # Test with send media group media = InputMediaPhoto(photo_file) with pytest.raises(ValueError, match="`reply_to_message_id` and"): - await bot.send_media_group( + await offline_bot.send_media_group( chat_id, media, reply_to_message_id=1, reply_parameters=True ) with pytest.raises(ValueError, match="`allow_sending_without_reply` and"): - await bot.send_media_group( + await offline_bot.send_media_group( chat_id, media, allow_sending_without_reply=True, reply_parameters=True ) # get_file is tested multiple times in the test_*media* modules. - # Here we only test the behaviour for bot apis in local mode - async def test_get_file_local_mode(self, bot, monkeypatch): + # Here we only test the behaviour for offline_bot apis in local mode + async def test_get_file_local_mode(self, offline_bot, monkeypatch): path = str(data_file("game.gif")) async def make_assertion(*args, **kwargs): @@ -1141,14 +1152,14 @@ class TestBotWithoutRequest: "file_path": path, } - monkeypatch.setattr(bot, "_post", make_assertion) + monkeypatch.setattr(offline_bot, "_post", make_assertion) - resulting_path = (await bot.get_file("file_id")).file_path - assert bot.token not in resulting_path + resulting_path = (await offline_bot.get_file("file_id")).file_path + assert offline_bot.token not in resulting_path assert resulting_path == path # TODO: Needs improvement. No feasible way to test until bots can add members. - async def test_ban_chat_member(self, monkeypatch, bot): + async def test_ban_chat_member(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "2" @@ -1157,13 +1168,13 @@ class TestBotWithoutRequest: revoke_msgs = data.get("revoke_messages", "true") == "true" return chat_id and user_id and until_date and revoke_msgs - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) until = from_timestamp(1577887200) - assert await bot.ban_chat_member(2, 32) - assert await bot.ban_chat_member(2, 32, until_date=until) - assert await bot.ban_chat_member(2, 32, until_date=1577887200) - assert await bot.ban_chat_member(2, 32, revoke_messages=True) + assert await offline_bot.ban_chat_member(2, 32) + assert await offline_bot.ban_chat_member(2, 32, until_date=until) + assert await offline_bot.ban_chat_member(2, 32, until_date=1577887200) + assert await offline_bot.ban_chat_member(2, 32, revoke_messages=True) async def test_ban_chat_member_default_tz(self, monkeypatch, tz_bot): until = dtm.datetime(2020, 1, 11, 16, 13) @@ -1182,7 +1193,7 @@ class TestBotWithoutRequest: assert await tz_bot.ban_chat_member(2, 32, until_date=until) assert await tz_bot.ban_chat_member(2, 32, until_date=until_timestamp) - async def test_ban_chat_sender_chat(self, monkeypatch, bot): + async def test_ban_chat_sender_chat(self, monkeypatch, offline_bot): # For now, we just test that we pass the correct data to TG async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters @@ -1190,12 +1201,12 @@ class TestBotWithoutRequest: sender_chat_id = data["sender_chat_id"] == 32 return chat_id and sender_chat_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.ban_chat_sender_chat(2, 32) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.ban_chat_sender_chat(2, 32) # TODO: Needs improvement. @pytest.mark.parametrize("only_if_banned", [True, False, None]) - async def test_unban_chat_member(self, monkeypatch, bot, only_if_banned): + async def test_unban_chat_member(self, monkeypatch, offline_bot, only_if_banned): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters chat_id = data["chat_id"] == 2 @@ -1203,21 +1214,21 @@ class TestBotWithoutRequest: o_i_b = data.get("only_if_banned", None) == only_if_banned return chat_id and user_id and o_i_b - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.unban_chat_member(2, 32, only_if_banned=only_if_banned) + assert await offline_bot.unban_chat_member(2, 32, only_if_banned=only_if_banned) - async def test_unban_chat_sender_chat(self, monkeypatch, bot): + async def test_unban_chat_sender_chat(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "2" sender_chat_id = data["sender_chat_id"] == "32" return chat_id and sender_chat_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.unban_chat_sender_chat(2, 32) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.unban_chat_sender_chat(2, 32) - async def test_set_chat_permissions(self, monkeypatch, bot, chat_permissions): + async def test_set_chat_permissions(self, monkeypatch, offline_bot, chat_permissions): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "2" @@ -1225,11 +1236,11 @@ class TestBotWithoutRequest: use_independent_chat_permissions = data["use_independent_chat_permissions"] return chat_id and permissions and use_independent_chat_permissions - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.set_chat_permissions(2, chat_permissions, True) + assert await offline_bot.set_chat_permissions(2, chat_permissions, True) - async def test_set_chat_administrator_custom_title(self, monkeypatch, bot): + async def test_set_chat_administrator_custom_title(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters chat_id = data["chat_id"] == 2 @@ -1237,11 +1248,11 @@ class TestBotWithoutRequest: custom_title = data["custom_title"] == "custom_title" return chat_id and user_id and custom_title - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.set_chat_administrator_custom_title(2, 32, "custom_title") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.set_chat_administrator_custom_title(2, 32, "custom_title") # TODO: Needs improvement. Need an incoming callbackquery to test - async def test_answer_callback_query(self, monkeypatch, bot): + async def test_answer_callback_query(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1252,27 +1263,27 @@ class TestBotWithoutRequest: "text": "answer", } - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_callback_query( + assert await offline_bot.answer_callback_query( 23, text="answer", show_alert=True, url="no_url", cache_time=1 ) @pytest.mark.parametrize("drop_pending_updates", [True, False]) async def test_set_webhook_delete_webhook_drop_pending_updates( - self, bot, drop_pending_updates, monkeypatch + self, offline_bot, drop_pending_updates, monkeypatch ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters return data.get("drop_pending_updates") == drop_pending_updates - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.set_webhook("", drop_pending_updates=drop_pending_updates) - assert await bot.delete_webhook(drop_pending_updates=drop_pending_updates) + assert await offline_bot.set_webhook("", drop_pending_updates=drop_pending_updates) + assert await offline_bot.delete_webhook(drop_pending_updates=drop_pending_updates) @pytest.mark.parametrize("local_file", ["str", "Path", False]) - async def test_set_webhook_params(self, bot, monkeypatch, local_file): + async def test_set_webhook_params(self, offline_bot, monkeypatch, local_file): # actually making calls to TG is done in # test_set_webhook_get_webhook_info_and_delete_webhook. Sadly secret_token can't be tested # there so we have this function \o/ @@ -1297,7 +1308,7 @@ class TestBotWithoutRequest: and kwargs["secret_token"] == "SoSecretToken" ) - monkeypatch.setattr(bot, "_post", make_assertion) + monkeypatch.setattr(offline_bot, "_post", make_assertion) cert_path = data_file("sslcert.pem") if local_file == "str": @@ -1307,7 +1318,7 @@ class TestBotWithoutRequest: else: certificate = cert_path.read_bytes() - assert await bot.set_webhook( + assert await offline_bot.set_webhook( "example.com", certificate, 7, @@ -1318,7 +1329,7 @@ class TestBotWithoutRequest: ) # TODO: Needs improvement. Need incoming shipping queries to test - async def test_answer_shipping_query_ok(self, monkeypatch, bot): + async def test_answer_shipping_query_ok(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1329,11 +1340,13 @@ class TestBotWithoutRequest: ], } - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) shipping_options = ShippingOption(1, "option1", [LabeledPrice("price", 100)]) - assert await bot.answer_shipping_query(1, True, shipping_options=[shipping_options]) + assert await offline_bot.answer_shipping_query( + 1, True, shipping_options=[shipping_options] + ) - async def test_answer_shipping_query_error_message(self, monkeypatch, bot): + async def test_answer_shipping_query_error_message(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1342,19 +1355,19 @@ class TestBotWithoutRequest: "ok": False, } - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.answer_shipping_query(1, False, error_message="Not enough fish") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.answer_shipping_query(1, False, error_message="Not enough fish") # TODO: Needs improvement. Need incoming pre checkout queries to test - async def test_answer_pre_checkout_query_ok(self, monkeypatch, bot): + async def test_answer_pre_checkout_query_ok(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == {"pre_checkout_query_id": 1, "ok": True} - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.answer_pre_checkout_query(1, True) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.answer_pre_checkout_query(1, True) - async def test_answer_pre_checkout_query_error_message(self, monkeypatch, bot): + async def test_answer_pre_checkout_query_error_message(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1363,10 +1376,12 @@ class TestBotWithoutRequest: "ok": False, } - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.answer_pre_checkout_query(1, False, error_message="Not enough fish") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.answer_pre_checkout_query( + 1, False, error_message="Not enough fish" + ) - async def test_restrict_chat_member(self, bot, chat_permissions, monkeypatch): + async def test_restrict_chat_member(self, offline_bot, chat_permissions, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "@chat" @@ -1382,9 +1397,9 @@ class TestBotWithoutRequest: and use_independent_chat_permissions ) - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.restrict_chat_member("@chat", 2, chat_permissions, 200, True) + assert await offline_bot.restrict_chat_member("@chat", 2, chat_permissions, 200, True) async def test_restrict_chat_member_default_tz( self, monkeypatch, tz_bot, channel_id, chat_permissions @@ -1406,10 +1421,10 @@ class TestBotWithoutRequest: ) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_set_chat_photo_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_set_chat_photo_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up self.test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -1420,13 +1435,13 @@ class TestBotWithoutRequest: else: self.test_flag = isinstance(data.get("photo"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.set_chat_photo(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.set_chat_photo(chat_id, file) assert self.test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False - async def test_timeout_propagation_explicit(self, monkeypatch, bot, chat_id): + async def test_timeout_propagation_explicit(self, monkeypatch, offline_bot, chat_id): # Use BaseException that's not a subclass of Exception such that # OkException should not be caught anywhere class OkException(BaseException): @@ -1441,19 +1456,19 @@ class TestBotWithoutRequest: return 200, b'{"ok": true, "result": []}' - monkeypatch.setattr(bot.request, "do_request", do_request) + monkeypatch.setattr(offline_bot.request, "do_request", do_request) # Test file uploading with pytest.raises(OkException): - await bot.send_photo( + await offline_bot.send_photo( chat_id, data_file("telegram.jpg").open("rb"), read_timeout=timeout ) # Test JSON submission with pytest.raises(OkException): - await bot.get_chat_administrators(chat_id, read_timeout=timeout) + await offline_bot.get_chat_administrators(chat_id, read_timeout=timeout) - async def test_timeout_propagation_implicit(self, monkeypatch, bot, chat_id): + async def test_timeout_propagation_implicit(self, monkeypatch, offline_bot, chat_id): # Use BaseException that's not a subclass of Exception such that # OkException should not be caught anywhere class OkException(BaseException): @@ -1467,33 +1482,34 @@ class TestBotWithoutRequest: return 200, b'{"ok": true, "result": []}' monkeypatch.setattr(httpx.AsyncClient, "request", request) + monkeypatch.setattr(offline_bot, "_request", (object(), HTTPXRequest())) # Test file uploading with pytest.raises(OkException): - await bot.send_photo(chat_id, data_file("telegram.jpg").open("rb")) + await offline_bot.send_photo(chat_id, data_file("telegram.jpg").open("rb")) - async def test_log_out(self, monkeypatch, bot): + async def test_log_out(self, monkeypatch, offline_bot): # We don't actually make a request as to not break the test setup async def assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters == {} and url.split("/")[-1] == "logOut" - monkeypatch.setattr(bot.request, "post", assertion) + monkeypatch.setattr(offline_bot.request, "post", assertion) - assert await bot.log_out() + assert await offline_bot.log_out() - async def test_close(self, monkeypatch, bot): + async def test_close(self, monkeypatch, offline_bot): # We don't actually make a request as to not break the test setup async def assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters == {} and url.split("/")[-1] == "close" - monkeypatch.setattr(bot.request, "post", assertion) + monkeypatch.setattr(offline_bot.request, "post", assertion) - assert await bot.close() + assert await offline_bot.close() @pytest.mark.parametrize("json_keyboard", [True, False]) @pytest.mark.parametrize("caption", ["Test", "", None]) async def test_copy_message( - self, monkeypatch, bot, chat_id, media_message, json_keyboard, caption + self, monkeypatch, offline_bot, chat_id, media_message, json_keyboard, caption ): keyboard = InlineKeyboardMarkup( [[InlineKeyboardButton(text="test", callback_data="test2")]] @@ -1525,8 +1541,8 @@ class TestBotWithoutRequest: pytest.fail("I got wrong parameters in post") return data - monkeypatch.setattr(bot.request, "post", post) - await bot.copy_message( + monkeypatch.setattr(offline_bot.request, "post", post) + await offline_bot.copy_message( chat_id, from_chat_id=chat_id, message_id=media_message.message_id, @@ -1557,7 +1573,7 @@ class TestBotWithoutRequest: async def test_arbitrary_callback_data_no_insert(self, monkeypatch, cdc_bot): """Updates that don't need insertion shouldn't fail obviously""" - bot = cdc_bot + offline_bot = cdc_bot async def post(*args, **kwargs): update = Update( @@ -1577,14 +1593,14 @@ class TestBotWithoutRequest: try: monkeypatch.setattr(BaseRequest, "post", post) - updates = await bot.get_updates(timeout=1) + updates = await offline_bot.get_updates(timeout=1) assert len(updates) == 1 assert updates[0].update_id == 17 assert updates[0].poll.id == "42" finally: - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() @pytest.mark.parametrize( "message_type", ["channel_post", "edited_channel_post", "message", "edited_message"] @@ -1592,7 +1608,7 @@ class TestBotWithoutRequest: async def test_arbitrary_callback_data_pinned_message_reply_to_message( self, cdc_bot, monkeypatch, message_type ): - bot = cdc_bot + offline_bot = cdc_bot reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="text", callback_data="callback_data") @@ -1602,11 +1618,11 @@ class TestBotWithoutRequest: 1, dtm.datetime.utcnow(), None, - reply_markup=bot.callback_data_cache.process_keyboard(reply_markup), + reply_markup=offline_bot.callback_data_cache.process_keyboard(reply_markup), ) message._unfreeze() # We do to_dict -> de_json to make sure those aren't the same objects - message.pinned_message = Message.de_json(message.to_dict(), bot) + message.pinned_message = Message.de_json(message.to_dict(), offline_bot) async def post(*args, **kwargs): update = Update( @@ -1617,7 +1633,7 @@ class TestBotWithoutRequest: dtm.datetime.utcnow(), None, pinned_message=message, - reply_to_message=Message.de_json(message.to_dict(), bot), + reply_to_message=Message.de_json(message.to_dict(), offline_bot), ) }, ) @@ -1625,7 +1641,7 @@ class TestBotWithoutRequest: try: monkeypatch.setattr(BaseRequest, "post", post) - updates = await bot.get_updates(timeout=1) + updates = await offline_bot.get_updates(timeout=1) assert isinstance(updates, tuple) assert len(updates) == 1 @@ -1646,11 +1662,11 @@ class TestBotWithoutRequest: ) finally: - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() async def test_get_updates_invalid_callback_data(self, cdc_bot, monkeypatch): - bot = cdc_bot + offline_bot = cdc_bot async def post(*args, **kwargs): return [ @@ -1674,7 +1690,7 @@ class TestBotWithoutRequest: try: monkeypatch.setattr(BaseRequest, "post", post) - updates = await bot.get_updates(timeout=1) + updates = await offline_bot.get_updates(timeout=1) assert isinstance(updates, tuple) assert len(updates) == 1 @@ -1682,12 +1698,12 @@ class TestBotWithoutRequest: finally: # Reset b/c bots scope is session - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() # TODO: Needs improvement. We need incoming inline query to test answer. async def test_replace_callback_data_answer_inline_query(self, monkeypatch, cdc_bot, chat_id): - bot = cdc_bot + offline_bot = cdc_bot # For now just test that our internals pass the correct data async def make_assertion( @@ -1704,7 +1720,7 @@ class TestBotWithoutRequest: inline_keyboard[0][0].callback_data[32:], ) assertion_3 = ( - bot.callback_data_cache._keyboard_data[keyboard].button_data[button] + offline_bot.callback_data_cache._keyboard_data[keyboard].button_data[button] == "replace_test" ) assertion_4 = data["results"][1].reply_markup is None @@ -1722,8 +1738,9 @@ class TestBotWithoutRequest: ] ) - bot.username # call this here so `bot.get_me()` won't be called after mocking - monkeypatch.setattr(bot, "_post", make_assertion) + # call this here so `offline_bot.get_me()` won't be called after mocking + offline_bot.username + monkeypatch.setattr(offline_bot, "_post", make_assertion) results = [ InlineQueryResultArticle( "11", "first", InputTextMessageContent("first"), reply_markup=reply_markup @@ -1735,11 +1752,11 @@ class TestBotWithoutRequest: ), ] - assert await bot.answer_inline_query(chat_id, results=results) + assert await offline_bot.answer_inline_query(chat_id, results=results) finally: - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() @pytest.mark.parametrize( "message_type", ["channel_post", "edited_channel_post", "message", "edited_message"] @@ -1813,7 +1830,7 @@ class TestBotWithoutRequest: assert warning.filename == __file__, "wrong stacklevel!" assert warning.category is PTBUserWarning - async def test_set_get_my_name(self, bot, monkeypatch): + async def test_set_get_my_name(self, offline_bot, monkeypatch): """We only test that we pass the correct values to TG since this endpoint is heavily rate limited which makes automated tests rather infeasible.""" default_name = "default_bot_name" @@ -1853,20 +1870,20 @@ class TestBotWithoutRequest: get_stack.task_done() return bot_name - monkeypatch.setattr(bot.request, "post", post) + monkeypatch.setattr(offline_bot.request, "post", post) # Set the names assert all( await asyncio.gather( - bot.set_my_name(default_name), - bot.set_my_name(en_name, language_code="en"), - bot.set_my_name(de_name, language_code="de"), + offline_bot.set_my_name(default_name), + offline_bot.set_my_name(en_name, language_code="en"), + offline_bot.set_my_name(de_name, language_code="de"), ) ) # Check that they were set correctly assert await asyncio.gather( - bot.get_my_name(), bot.get_my_name("en"), bot.get_my_name("de") + offline_bot.get_my_name(), offline_bot.get_my_name("en"), offline_bot.get_my_name("de") ) == [ BotName(default_name), BotName(en_name), @@ -1876,18 +1893,18 @@ class TestBotWithoutRequest: # Delete the names assert all( await asyncio.gather( - bot.set_my_name(default_name), - bot.set_my_name(None, language_code="en"), - bot.set_my_name(None, language_code="de"), + offline_bot.set_my_name(default_name), + offline_bot.set_my_name(None, language_code="en"), + offline_bot.set_my_name(None, language_code="de"), ) ) # Check that they were deleted correctly assert await asyncio.gather( - bot.get_my_name(), bot.get_my_name("en"), bot.get_my_name("de") + offline_bot.get_my_name(), offline_bot.get_my_name("en"), offline_bot.get_my_name("de") ) == 3 * [BotName(default_name)] - async def test_set_message_reaction(self, bot, monkeypatch): + async def test_set_message_reaction(self, offline_bot, monkeypatch): """This is here so we can test the convenient conversion we do in the function without having to do multiple requests to Telegram""" @@ -1918,14 +1935,22 @@ class TestBotWithoutRequest: assert request_data.parameters["reaction"] == expected_param[amount] amount += 1 - monkeypatch.setattr(bot.request, "post", post) - await bot.set_message_reaction(1, 2, [ReactionTypeEmoji(ReactionEmoji.THUMBS_UP)], True) - await bot.set_message_reaction(1, 2, ReactionTypeEmoji(ReactionEmoji.RED_HEART), True) - await bot.set_message_reaction(1, 2, [ReactionTypeCustomEmoji("custom_emoji_1")], True) - await bot.set_message_reaction(1, 2, ReactionTypeCustomEmoji("custom_emoji_2"), True) - await bot.set_message_reaction(1, 2, ReactionEmoji.THUMBS_DOWN, True) - await bot.set_message_reaction(1, 2, "custom_emoji_3", True) - await bot.set_message_reaction( + monkeypatch.setattr(offline_bot.request, "post", post) + await offline_bot.set_message_reaction( + 1, 2, [ReactionTypeEmoji(ReactionEmoji.THUMBS_UP)], True + ) + await offline_bot.set_message_reaction( + 1, 2, ReactionTypeEmoji(ReactionEmoji.RED_HEART), True + ) + await offline_bot.set_message_reaction( + 1, 2, [ReactionTypeCustomEmoji("custom_emoji_1")], True + ) + await offline_bot.set_message_reaction( + 1, 2, ReactionTypeCustomEmoji("custom_emoji_2"), True + ) + await offline_bot.set_message_reaction(1, 2, ReactionEmoji.THUMBS_DOWN, True) + await offline_bot.set_message_reaction(1, 2, "custom_emoji_3", True) + await offline_bot.set_message_reaction( 1, 2, [ @@ -2047,7 +2072,7 @@ class TestBotWithoutRequest: reply_parameters=ReplyParameters(**kwargs), ) - async def test_send_poll_question_parse_mode_entities(self, bot, monkeypatch): + async def test_send_poll_question_parse_mode_entities(self, offline_bot, monkeypatch): # Currently only custom emoji are supported as entities which we can't test # We just test that the correct data is passed for now @@ -2059,8 +2084,8 @@ class TestBotWithoutRequest: assert request_data.parameters["question_parse_mode"] == ParseMode.MARKDOWN_V2 return make_message("dummy reply").to_dict() - monkeypatch.setattr(bot.request, "post", make_assertion) - await bot.send_poll( + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + await offline_bot.send_poll( 1, question="😀😃", options=["option1", "option2"], @@ -2123,15 +2148,15 @@ class TestBotWithoutRequest: monkeypatch.setattr(default_bot.request, "post", make_assertion) await default_bot.copy_message(chat_id, 1, 1, reply_parameters=ReplyParameters(**kwargs)) - async def test_do_api_request_camel_case_conversion(self, bot, monkeypatch): + async def test_do_api_request_camel_case_conversion(self, offline_bot, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return url.endswith("camelCase") - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.do_api_request("camel_case") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.do_api_request("camel_case") @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") - async def test_do_api_request_media_write_timeout(self, bot, chat_id, monkeypatch): + async def test_do_api_request_media_write_timeout(self, offline_bot, chat_id, monkeypatch): test_flag = None class CustomRequest(BaseRequest): @@ -2153,8 +2178,8 @@ class TestBotWithoutRequest: custom_request = CustomRequest() - bot = Bot(bot.token, request=custom_request) - await bot.do_api_request( + offline_bot = Bot(offline_bot.token, request=custom_request) + await offline_bot.do_api_request( "send_document", api_kwargs={ "chat_id": chat_id, @@ -2194,7 +2219,7 @@ class TestBotWithoutRequest: api_kwargs={"chat_id": 2, "user_id": 32, "until_date": until_timestamp}, ) - async def test_business_connection_id_argument(self, bot, monkeypatch): + async def test_business_connection_id_argument(self, offline_bot, monkeypatch): """We can't connect to a business acc, so we just test that the correct data is passed. We also can't test every single method easily, so we just test a few. Our linting will catch any unused args with the others.""" @@ -2203,24 +2228,24 @@ class TestBotWithoutRequest: assert request_data.parameters.get("business_connection_id") == 42 return {} - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - await bot.send_message(2, "text", business_connection_id=42) - await bot.stop_poll(chat_id=1, message_id=2, business_connection_id=42) - await bot.pin_chat_message(chat_id=1, message_id=2, business_connection_id=42) - await bot.unpin_chat_message(chat_id=1, business_connection_id=42) + await offline_bot.send_message(2, "text", business_connection_id=42) + await offline_bot.stop_poll(chat_id=1, message_id=2, business_connection_id=42) + await offline_bot.pin_chat_message(chat_id=1, message_id=2, business_connection_id=42) + await offline_bot.unpin_chat_message(chat_id=1, business_connection_id=42) - async def test_message_effect_id_argument(self, bot, monkeypatch): + async def test_message_effect_id_argument(self, offline_bot, monkeypatch): """We can't test every single method easily, so we just test one. Our linting will catch any unused args with the others.""" async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters.get("message_effect_id") == 42 - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_message(2, "text", message_effect_id=42) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_message(2, "text", message_effect_id=42) - async def test_get_business_connection(self, bot, monkeypatch): + async def test_get_business_connection(self, offline_bot, monkeypatch): bci = "42" user = User(1, "first", False) user_chat_id = 1 @@ -2236,11 +2261,11 @@ class TestBotWithoutRequest: return 200, f'{{"ok": true, "result": {bc}}}'.encode() return 400, b'{"ok": false, "result": []}' - monkeypatch.setattr(bot.request, "do_request", do_request) - obj = await bot.get_business_connection(business_connection_id=bci) + monkeypatch.setattr(offline_bot.request, "do_request", do_request) + obj = await offline_bot.get_business_connection(business_connection_id=bci) assert isinstance(obj, BusinessConnection) - async def test_refund_star_payment(self, bot, monkeypatch): + async def test_refund_star_payment(self, offline_bot, monkeypatch): # can't make actual request so we just test that the correct data is passed async def make_assertion(url, request_data: RequestData, *args, **kwargs): return ( @@ -2248,10 +2273,10 @@ class TestBotWithoutRequest: and request_data.parameters.get("telegram_payment_charge_id") == "37" ) - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.refund_star_payment(42, "37") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.refund_star_payment(42, "37") - async def test_get_star_transactions(self, bot, monkeypatch): + async def test_get_star_transactions(self, offline_bot, monkeypatch): # we just want to test the offset parameter st = StarTransactions([StarTransaction("1", 1, dtm.datetime.now())]).to_json() @@ -2261,14 +2286,14 @@ class TestBotWithoutRequest: return 200, f'{{"ok": true, "result": {st}}}'.encode() return 400, b'{"ok": false, "result": []}' - monkeypatch.setattr(bot.request, "do_request", do_request) - obj = await bot.get_star_transactions(offset=3) + monkeypatch.setattr(offline_bot.request, "do_request", do_request) + obj = await offline_bot.get_star_transactions(offset=3) assert isinstance(obj, StarTransactions) async def test_create_chat_subscription_invite_link( self, monkeypatch, - bot, + offline_bot, ): # Since the chat invite link object does not say if the sub args are passed we can # only check here @@ -2276,9 +2301,9 @@ class TestBotWithoutRequest: assert request_data.parameters.get("subscription_period") == 2592000 assert request_data.parameters.get("subscription_price") == 6 - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - await bot.create_chat_subscription_invite_link(1234, 2592000, 6) + await offline_bot.create_chat_subscription_invite_link(1234, 2592000, 6) class TestBotWithRequest: diff --git a/tests/test_botcommand.py b/tests/test_botcommand.py index 1e4a360e0..f38abb320 100644 --- a/tests/test_botcommand.py +++ b/tests/test_botcommand.py @@ -37,15 +37,15 @@ class TestBotCommandWithoutRequest: 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" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): 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.command == self.command 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): bot_command_dict = bot_command.to_dict() diff --git a/tests/test_botcommandscope.py b/tests/test_botcommandscope.py index 63766b95e..a4bddfc8f 100644 --- a/tests/test_botcommandscope.py +++ b/tests/test_botcommandscope.py @@ -125,14 +125,14 @@ class TestBotCommandScopeWithoutRequest: set(mro_slots(bot_command_scope)) ), "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] 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} - 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( cls.__slots__ ) @@ -145,18 +145,18 @@ class TestBotCommandScopeWithoutRequest: if "user_id" in cls.__slots__: 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} - 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 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 BotCommandScopeChat instance.""" 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): bot_command_scope_dict = bot_command_scope.to_dict() @@ -172,7 +172,7 @@ class TestBotCommandScopeWithoutRequest: assert type(BotCommandScope("default").type) is BotCommandScopeType 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") b = BotCommandScope("base_type") c = bot_command_scope @@ -200,7 +200,7 @@ class TestBotCommandScopeWithoutRequest: if hasattr(c, "chat_id"): json_dict = c.to_dict() 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 hash(c) != hash(f) @@ -208,7 +208,7 @@ class TestBotCommandScopeWithoutRequest: if hasattr(c, "user_id"): json_dict = c.to_dict() 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 hash(c) != hash(g) diff --git a/tests/test_business.py b/tests/test_business.py index 735f2e717..e3da36948 100644 --- a/tests/test_business.py +++ b/tests/test_business.py @@ -139,7 +139,7 @@ class TestBusinessConnectionWithoutRequest(BusinessTestBase): assert bc.api_kwargs == {} 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 = { "id": self.id_, "user": self.user.to_dict(), @@ -148,7 +148,7 @@ class TestBusinessConnectionWithoutRequest(BusinessTestBase): "can_reply": self.can_reply, "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_tz = BusinessConnection.de_json(json_dict, tz_bot) diff --git a/tests/test_callbackquery.py b/tests/test_callbackquery.py index 3131b34f2..7a53651a3 100644 --- a/tests/test_callbackquery.py +++ b/tests/test_callbackquery.py @@ -94,7 +94,7 @@ class TestCallbackQueryWithoutRequest(CallbackQueryTestBase): 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" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "from": self.from_user.to_dict(), @@ -104,7 +104,7 @@ class TestCallbackQueryWithoutRequest(CallbackQueryTestBase): "inline_message_id": self.inline_message_id, "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.id == self.id_ diff --git a/tests/test_chat.py b/tests/test_chat.py index a3dcd6aa1..adf2c42bc 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -63,7 +63,7 @@ class TestChatWithoutRequest(ChatTestBase): assert getattr(chat, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "id": self.id_, "title": self.title, @@ -73,7 +73,7 @@ class TestChatWithoutRequest(ChatTestBase): "first_name": self.first_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.title == self.title diff --git a/tests/test_chatadministratorrights.py b/tests/test_chatadministratorrights.py index e630693c2..e15de43c7 100644 --- a/tests/test_chatadministratorrights.py +++ b/tests/test_chatadministratorrights.py @@ -50,7 +50,7 @@ class TestChatAdministratorRightsWithoutRequest: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "can_change_info": True, "can_delete_messages": True, @@ -68,7 +68,7 @@ class TestChatAdministratorRightsWithoutRequest: "can_edit_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_admin_rights == chat_administrator_rights_de diff --git a/tests/test_chatbackground.py b/tests/test_chatbackground.py index 900fc5870..ccf90d411 100644 --- a/tests/test_chatbackground.py +++ b/tests/test_chatbackground.py @@ -168,12 +168,12 @@ class TestBackgroundTypeWithoutRequest: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None 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 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): 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) - 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 == {} @@ -194,19 +194,19 @@ class TestBackgroundTypeWithoutRequest: ): 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} - background_type = BackgroundType.de_json(json_dict, bot) + background_type = BackgroundType.de_json(json_dict, offline_bot) assert type(background_type) is BackgroundType assert background_type.type == "invalid" - def test_de_json_subclass(self, background_type, bot, chat_id): - """This makes sure that e.g. BackgroundTypeFill(data, bot) never returns a + def test_de_json_subclass(self, background_type, offline_bot, chat_id): + """This makes sure that e.g. BackgroundTypeFill(data, offline_bot) never returns a BackgroundTypeWallpaper instance.""" cls = background_type.__class__ 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): 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 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__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None 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 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): 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) - 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 == {} @@ -301,19 +301,19 @@ class TestBackgroundFillWithoutRequest: ): 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} - background_fill = BackgroundFill.de_json(json_dict, bot) + background_fill = BackgroundFill.de_json(json_dict, offline_bot) assert type(background_fill) is BackgroundFill assert background_fill.type == "invalid" - def test_de_json_subclass(self, background_fill, bot): - """This makes sure that e.g. BackgroundFillSolid(data, bot) never returns a + def test_de_json_subclass(self, background_fill, offline_bot): + """This makes sure that e.g. BackgroundFillSolid(data, offline_bot) never returns a BackgroundFillGradient instance.""" cls = background_fill.__class__ 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): bg_fill_dict = background_fill.to_dict() diff --git a/tests/test_chatboost.py b/tests/test_chatboost.py index f0ef14361..62123df73 100644 --- a/tests/test_chatboost.py +++ b/tests/test_chatboost.py @@ -170,13 +170,13 @@ class TestChatBoostSourceTypesWithoutRequest: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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__ - assert cls.de_json({}, bot) is None - assert ChatBoost.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None + assert ChatBoost.de_json({}, offline_bot) is None 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 isinstance(const_boost_source, ChatBoostSource) @@ -186,9 +186,9 @@ class TestChatBoostSourceTypesWithoutRequest: ): 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) - 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 isinstance(const_boost_source, ChatBoostSource) @@ -198,19 +198,19 @@ class TestChatBoostSourceTypesWithoutRequest: ): 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"} - 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 chat_boost_source.source == "invalid" - def test_de_json_subclass(self, chat_boost_source, bot): - """This makes sure that e.g. ChatBoostSourcePremium(data, bot) never returns a + def test_de_json_subclass(self, chat_boost_source, offline_bot): + """This makes sure that e.g. ChatBoostSourcePremium(data, offline_bot) never returns a ChatBoostSourceGiftCode instance.""" cls = chat_boost_source.__class__ 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): 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 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 = { "boost_id": "2", "add_date": self.date, "expiration_date": self.date, "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.add_date, datetime.datetime) @@ -284,7 +284,7 @@ class TestChatBoostWithoutRequest(ChatBoostDefaults): for slot in cb.__slots__: 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 = { "boost_id": "2", "add_date": self.date, @@ -292,7 +292,7 @@ class TestChatBoostWithoutRequest(ChatBoostDefaults): "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_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 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 = { "chat": self.chat.to_dict(), "boost": { @@ -357,7 +357,7 @@ class TestChatBoostUpdatedWithoutRequest(ChatBoostDefaults): "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 cbu.chat == self.chat @@ -420,14 +420,14 @@ class TestChatBoostRemovedWithoutRequest(ChatBoostDefaults): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "chat": self.chat.to_dict(), "boost_id": "2", "remove_date": self.date, "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 cbr.chat == self.chat @@ -435,7 +435,7 @@ class TestChatBoostRemovedWithoutRequest(ChatBoostDefaults): assert to_timestamp(cbr.remove_date) == self.date 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 = { "chat": self.chat.to_dict(), "boost_id": "2", @@ -443,7 +443,7 @@ class TestChatBoostRemovedWithoutRequest(ChatBoostDefaults): "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_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 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 = { "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.boosts[0], ChatBoost) @@ -525,7 +525,7 @@ class TestUserChatBoostsWithoutRequest(ChatBoostDefaults): assert isinstance(user_chat_boosts_dict["boosts"], list) 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): data = request_data.json_parameters chat_id = data["chat_id"] == "3" @@ -534,9 +534,9 @@ class TestUserChatBoostsWithoutRequest(ChatBoostDefaults): pytest.fail("I got wrong parameters in post") 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): diff --git a/tests/test_chatfullinfo.py b/tests/test_chatfullinfo.py index 7e5bc90ba..6c1054930 100644 --- a/tests/test_chatfullinfo.py +++ b/tests/test_chatfullinfo.py @@ -150,7 +150,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase): 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 = { "id": self.id_, "title": self.title, @@ -194,7 +194,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase): "last_name": self.last_name, "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.title == self.title assert cfi.type == self.type_ @@ -239,7 +239,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase): assert cfi.max_reaction_count == self.max_reaction_count 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 = { "id": self.id_, "type": self.type_, @@ -247,7 +247,7 @@ class TestChatFullInfoWithoutRequest(ChatFullInfoTestBase): "max_reaction_count": self.max_reaction_count, "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_tz = ChatFullInfo.de_json(json_dict, tz_bot) diff --git a/tests/test_chatinvitelink.py b/tests/test_chatinvitelink.py index 9331166b4..86ca7afd3 100644 --- a/tests/test_chatinvitelink.py +++ b/tests/test_chatinvitelink.py @@ -66,7 +66,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase): 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" - def test_de_json_required_args(self, bot, creator): + def test_de_json_required_args(self, offline_bot, creator): json_dict = { "invite_link": self.link, "creator": creator.to_dict(), @@ -75,7 +75,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase): "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.invite_link == self.link @@ -84,7 +84,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase): assert invite_link.is_primary == self.primary 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 = { "invite_link": self.link, "creator": creator.to_dict(), @@ -99,7 +99,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase): "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.invite_link == self.link @@ -115,7 +115,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase): assert invite_link.subscription_period == self.subscription_period 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 = { "invite_link": self.link, "creator": creator.to_dict(), @@ -129,7 +129,7 @@ class TestChatInviteLinkWithoutRequest(ChatInviteLinkTestBase): } 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) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_chatjoinrequest.py b/tests/test_chatjoinrequest.py index cdf2787e8..cf0550c30 100644 --- a/tests/test_chatjoinrequest.py +++ b/tests/test_chatjoinrequest.py @@ -70,14 +70,14 @@ class TestChatJoinRequestWithoutRequest(ChatJoinRequestTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "chat": self.chat.to_dict(), "from": self.from_user.to_dict(), "date": to_timestamp(time), "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.chat == self.chat @@ -87,7 +87,7 @@ class TestChatJoinRequestWithoutRequest(ChatJoinRequestTestBase): assert chat_join_request.user_chat_id == self.from_user.id 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.chat == self.chat @@ -98,7 +98,7 @@ class TestChatJoinRequestWithoutRequest(ChatJoinRequestTestBase): assert chat_join_request.bio == self.bio 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 = { "chat": self.chat.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_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) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_chatlocation.py b/tests/test_chatlocation.py index 00481d644..b83306308 100644 --- a/tests/test_chatlocation.py +++ b/tests/test_chatlocation.py @@ -40,12 +40,12 @@ class TestChatLocationWithoutRequest(ChatLocationTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "location": self.location.to_dict(), "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.location == self.location diff --git a/tests/test_chatmember.py b/tests/test_chatmember.py index 4296fdd27..2058d4bdf 100644 --- a/tests/test_chatmember.py +++ b/tests/test_chatmember.py @@ -205,12 +205,12 @@ class TestChatMemberTypesWithoutRequest: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None 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 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): 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) - 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 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): 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. if isinstance( chat_member_type, (ChatMemberBanned, ChatMemberRestricted, ChatMemberMember) ): json_dict = make_json_dict(chat_member_type, include_optional_args=True) 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) # comparing utcoffsets because comparing timezones is unpredicatable @@ -248,19 +250,19 @@ class TestChatMemberTypesWithoutRequest: assert chatmember_bot.until_date.tzinfo == UTC 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()} - 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 chat_member_type.status == "invalid" - def test_de_json_subclass(self, chat_member_type, bot, chat_id): - """This makes sure that e.g. ChatMemberAdministrator(data, bot) never returns a + def test_de_json_subclass(self, chat_member_type, offline_bot, chat_id): + """This makes sure that e.g. ChatMemberAdministrator(data, offline_bot) never returns a ChatMemberBanned instance.""" cls = chat_member_type.__class__ 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): chat_member_dict = chat_member_type.to_dict() diff --git a/tests/test_chatmemberupdated.py b/tests/test_chatmemberupdated.py index 33b07863a..7bdd704fb 100644 --- a/tests/test_chatmemberupdated.py +++ b/tests/test_chatmemberupdated.py @@ -99,7 +99,9 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase): assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "chat": chat.to_dict(), "from": user.to_dict(), @@ -108,7 +110,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase): "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.chat == chat @@ -121,7 +123,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase): assert chat_member_updated.via_chat_folder_invite_link is None 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 = { "chat": chat.to_dict(), @@ -134,7 +136,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase): "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.chat == chat @@ -148,7 +150,16 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase): assert chat_member_updated.via_join_request is True 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 = { "chat": chat.to_dict(), @@ -159,7 +170,7 @@ class TestChatMemberUpdatedWithoutRequest(ChatMemberUpdatedTestBase): "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_tz = ChatMemberUpdated.de_json(json_dict, tz_bot) diff --git a/tests/test_chatpermissions.py b/tests/test_chatpermissions.py index 79b6bab80..fcb93840f 100644 --- a/tests/test_chatpermissions.py +++ b/tests/test_chatpermissions.py @@ -67,7 +67,7 @@ class TestChatPermissionsWithoutRequest(ChatPermissionsTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "can_send_messages": self.can_send_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_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.can_send_messages == self.can_send_messages diff --git a/tests/test_choseninlineresult.py b/tests/test_choseninlineresult.py index 2b53b6847..8d6529c10 100644 --- a/tests/test_choseninlineresult.py +++ b/tests/test_choseninlineresult.py @@ -49,16 +49,16 @@ class TestChosenInlineResultWithoutRequest(ChosenInlineResultTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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} - result = ChosenInlineResult.de_json(json_dict, bot) + result = ChosenInlineResult.de_json(json_dict, offline_bot) assert result.api_kwargs == {} assert result.result_id == self.result_id assert result.from_user == user 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) json_dict = { "result_id": self.result_id, @@ -67,7 +67,7 @@ class TestChosenInlineResultWithoutRequest(ChosenInlineResultTestBase): "location": loc.to_dict(), "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.result_id == self.result_id diff --git a/tests/test_dice.py b/tests/test_dice.py index df3c349d4..de82d29ae 100644 --- a/tests/test_dice.py +++ b/tests/test_dice.py @@ -39,14 +39,14 @@ class TestDiceWithoutRequest(DiceTestBase): assert len(mro_slots(dice)) == len(set(mro_slots(dice))), "duplicate slot" @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} - dice = Dice.de_json(json_dict, bot) + dice = Dice.de_json(json_dict, offline_bot) assert dice.api_kwargs == {} assert dice.value == self.value 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): dice_dict = dice.to_dict() diff --git a/tests/test_forum.py b/tests/test_forum.py index 1f143616e..4fd65c5d8 100644 --- a/tests/test_forum.py +++ b/tests/test_forum.py @@ -86,8 +86,8 @@ class TestForumTopicWithoutRequest: assert forum_topic_object.name == TEST_TOPIC_NAME assert forum_topic_object.icon_custom_emoji_id == emoji_id - def test_de_json(self, bot, emoji_id, forum_group_id): - assert ForumTopic.de_json(None, bot=bot) is None + def test_de_json(self, offline_bot, emoji_id, forum_group_id): + assert ForumTopic.de_json(None, bot=offline_bot) is None json_dict = { "message_thread_id": forum_group_id, @@ -95,7 +95,7 @@ class TestForumTopicWithoutRequest: "icon_color": TEST_TOPIC_ICON_COLOR, "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.message_thread_id == forum_group_id @@ -333,11 +333,11 @@ class TestForumTopicCreatedWithoutRequest: assert topic_created.icon_color == TEST_TOPIC_ICON_COLOR assert topic_created.name == TEST_TOPIC_NAME - def test_de_json(self, bot): - assert ForumTopicCreated.de_json(None, bot=bot) is None + def test_de_json(self, offline_bot): + assert ForumTopicCreated.de_json(None, bot=offline_bot) is None 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.icon_color == TEST_TOPIC_ICON_COLOR diff --git a/tests/test_giveaway.py b/tests/test_giveaway.py index 359451183..4aac4150c 100644 --- a/tests/test_giveaway.py +++ b/tests/test_giveaway.py @@ -66,7 +66,7 @@ class TestGiveawayWithoutRequest: assert getattr(giveaway, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "chats": [chat.to_dict() for chat in self.chats], "winners_selection_date": to_timestamp(self.winners_selection_date), @@ -78,7 +78,7 @@ class TestGiveawayWithoutRequest: "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.chats == tuple(self.chats) @@ -90,9 +90,9 @@ class TestGiveawayWithoutRequest: assert giveaway.country_codes == tuple(self.country_codes) 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 = { "chats": [chat.to_dict() for chat in self.chats], "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_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) # comparing utcoffsets because comparing timezones is unpredicatable @@ -213,7 +213,7 @@ class TestGiveawayWinnersWithoutRequest: set(mro_slots(giveaway_winners)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "chat": self.chat.to_dict(), "giveaway_message_id": self.giveaway_message_id, @@ -228,7 +228,7 @@ class TestGiveawayWinnersWithoutRequest: "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.chat == self.chat @@ -246,9 +246,9 @@ class TestGiveawayWinnersWithoutRequest: assert giveaway_winners.was_refunded == self.was_refunded 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 = { "chat": self.chat.to_dict(), "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_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) # comparing utcoffsets because comparing timezones is unpredicatable @@ -357,21 +357,21 @@ class TestGiveawayCompletedWithoutRequest: set(mro_slots(giveaway_completed)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "winner_count": self.winner_count, "unclaimed_prize_count": self.unclaimed_prize_count, "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.winner_count == self.winner_count assert giveaway_completed.unclaimed_prize_count == self.unclaimed_prize_count 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): giveaway_completed_dict = giveaway_completed.to_dict() diff --git a/tests/test_inlinequeryresultsbutton.py b/tests/test_inlinequeryresultsbutton.py index 90ce2c235..1ec59573a 100644 --- a/tests/test_inlinequeryresultsbutton.py +++ b/tests/test_inlinequeryresultsbutton.py @@ -51,16 +51,16 @@ class TestInlineQueryResultsButtonWithoutRequest(InlineQueryResultsButtonTestBas assert inline_query_results_button_dict["start_parameter"] == self.start_parameter assert inline_query_results_button_dict["web_app"] == self.web_app.to_dict() - def test_de_json(self, bot): - assert InlineQueryResultsButton.de_json(None, bot) is None - assert InlineQueryResultsButton.de_json({}, bot) is None + def test_de_json(self, offline_bot): + assert InlineQueryResultsButton.de_json(None, offline_bot) is None + assert InlineQueryResultsButton.de_json({}, offline_bot) is None json_dict = { "text": self.text, "start_parameter": self.start_parameter, "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.start_parameter == self.start_parameter diff --git a/tests/test_keyboardbutton.py b/tests/test_keyboardbutton.py index 4493ed223..91f5ccab7 100644 --- a/tests/test_keyboardbutton.py +++ b/tests/test_keyboardbutton.py @@ -81,7 +81,7 @@ class TestKeyboardButtonWithoutRequest(KeyboardButtonTestBase): assert keyboard_button_dict["request_users"] == keyboard_button.request_users.to_dict() @pytest.mark.parametrize("request_user", [True, False]) - def test_de_json(self, bot, request_user): + def test_de_json(self, request_user): json_dict = { "text": self.text, "request_location": self.request_location, diff --git a/tests/test_keyboardbuttonrequest.py b/tests/test_keyboardbuttonrequest.py index 8e42b1cd3..9d9a02952 100644 --- a/tests/test_keyboardbuttonrequest.py +++ b/tests/test_keyboardbuttonrequest.py @@ -57,14 +57,14 @@ class TestKeyboardButtonRequestUsersWithoutRequest(KeyboardButtonRequestUsersTes assert request_users_dict["user_is_premium"] == self.user_is_premium assert request_users_dict["max_quantity"] == self.max_quantity - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "request_id": self.request_id, "user_is_bot": self.user_is_bot, "user_is_premium": self.user_is_premium, "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.request_id == self.request_id @@ -158,7 +158,7 @@ class TestKeyboardButtonRequestChatWithoutRequest(KeyboardButtonRequestChatTestB ) 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 = { "request_id": self.request_id, "chat_is_channel": self.chat_is_channel, @@ -168,7 +168,7 @@ class TestKeyboardButtonRequestChatWithoutRequest(KeyboardButtonRequestChatTestB "bot_administrator_rights": self.bot_administrator_rights.to_dict(), "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.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_is_member == self.bot_is_member - empty_chat = KeyboardButtonRequestChat.de_json({}, bot) + empty_chat = KeyboardButtonRequestChat.de_json({}, offline_bot) assert empty_chat is None def test_equality(self): diff --git a/tests/test_maybeinaccessiblemessage.py b/tests/test_maybeinaccessiblemessage.py index da7db43ce..8cad89e88 100644 --- a/tests/test_maybeinaccessiblemessage.py +++ b/tests/test_maybeinaccessiblemessage.py @@ -59,20 +59,20 @@ class TestMaybeInaccessibleMessageWithoutRequest(MaybeInaccessibleMessageTestBas assert maybe_inaccessible_message_dict["message_id"] == self.message_id 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 = { "chat": self.chat.to_dict(), "message_id": self.message_id, "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.chat == self.chat assert maybe_inaccessible_message.message_id == self.message_id 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 = { "chat": self.chat.to_dict(), "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_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) # 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_tz_offset == tz_bot_offset - def test_de_json_zero_date(self, bot): + def test_de_json_zero_date(self, offline_bot): json_dict = { "chat": self.chat.to_dict(), "message_id": self.message_id, "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 is ZERO_DATE diff --git a/tests/test_menubutton.py b/tests/test_menubutton.py index d5930f805..d9ae7c1ef 100644 --- a/tests/test_menubutton.py +++ b/tests/test_menubutton.py @@ -103,12 +103,12 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase): 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" - 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] type_ = scope_class_and_type[1] 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 isinstance(menu_button, MenuButton) @@ -119,22 +119,22 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase): if "text" in cls.__slots__: assert menu_button.text == self.text - assert cls.de_json(None, bot) is None - assert MenuButton.de_json({}, bot) is None + assert cls.de_json(None, offline_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()} - 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 type(menu_button) is MenuButton 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 MenuButtonChat instance.""" 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): if scope_class in (MenuButtonWebApp,): @@ -157,7 +157,7 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase): assert type(MenuButton("commands").type) is MenuButtonType assert MenuButton("unknown").type == "unknown" - def test_equality(self, menu_button, bot): + def test_equality(self, menu_button, offline_bot): a = MenuButton("base_type") b = MenuButton("base_type") c = menu_button @@ -185,7 +185,7 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase): if hasattr(c, "web_app"): json_dict = c.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 hash(c) != hash(f) @@ -193,7 +193,7 @@ class TestMenuButtonWithoutRequest(MenuButtonTestBase): if hasattr(c, "text"): json_dict = c.to_dict() 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 hash(c) != hash(g) diff --git a/tests/test_message.py b/tests/test_message.py index 84b2b7c39..02d6e5b5f 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -568,8 +568,8 @@ class TestMessageWithoutRequest(MessageTestBase): assert getattr(message, attr, "err") != "err", f"got extra slot '{attr}'" 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): - new = Message.de_json(message_params.to_dict(), bot) + def test_all_possibilities_de_json_and_to_dict(self, offline_bot, message_params): + new = Message.de_json(message_params.to_dict(), offline_bot) assert new.api_kwargs == {} assert new.to_dict() == message_params.to_dict() @@ -579,7 +579,7 @@ class TestMessageWithoutRequest(MessageTestBase): for slot in new.__slots__: 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 = { "message_id": 12, "from_user": None, @@ -589,7 +589,7 @@ class TestMessageWithoutRequest(MessageTestBase): } 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) # comparing utcoffsets because comparing timezones is unpredicatable @@ -609,7 +609,7 @@ class TestMessageWithoutRequest(MessageTestBase): assert message_bot.edit_date.tzinfo == UTC 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() keys = ( "user_shared", @@ -622,7 +622,7 @@ class TestMessageWithoutRequest(MessageTestBase): ) for key in keys: 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} def test_equality(self): @@ -2653,10 +2653,10 @@ class TestMessageWithoutRequest(MessageTestBase): ], ) 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() - 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) async def make_assertion(*_, **kwargs): diff --git a/tests/test_messageentity.py b/tests/test_messageentity.py index 3598454d8..4c981f453 100644 --- a/tests/test_messageentity.py +++ b/tests/test_messageentity.py @@ -55,9 +55,9 @@ class TestMessageEntityWithoutRequest(MessageEntityTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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} - entity = MessageEntity.de_json(json_dict, bot) + entity = MessageEntity.de_json(json_dict, offline_bot) assert entity.api_kwargs == {} assert entity.type == self.type_ diff --git a/tests/test_messageorigin.py b/tests/test_messageorigin.py index 10d9fa778..7b239bc37 100644 --- a/tests/test_messageorigin.py +++ b/tests/test_messageorigin.py @@ -136,12 +136,12 @@ class TestMessageOriginTypesWithoutRequest: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None 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 isinstance(const_message_origin, MessageOrigin) @@ -151,9 +151,9 @@ class TestMessageOriginTypesWithoutRequest: ): 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) - 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 == {} @@ -164,10 +164,12 @@ class TestMessageOriginTypesWithoutRequest: ): 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) 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) # comparing utcoffsets because comparing timezones is unpredicatable @@ -178,19 +180,19 @@ class TestMessageOriginTypesWithoutRequest: assert msgorigin_bot.date.tzinfo == UTC 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} - 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 message_origin_type.type == "invalid" - def test_de_json_subclass(self, message_origin_type, bot, chat_id): - """This makes sure that e.g. MessageOriginChat(data, bot) never returns a + def test_de_json_subclass(self, message_origin_type, offline_bot, chat_id): + """This makes sure that e.g. MessageOriginChat(data, offline_bot) never returns a MessageOriginUser instance.""" cls = message_origin_type.__class__ 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): message_origin_dict = message_origin_type.to_dict() diff --git a/tests/test_paidmedia.py b/tests/test_paidmedia.py index be9ac1490..6592125e7 100644 --- a/tests/test_paidmedia.py +++ b/tests/test_paidmedia.py @@ -150,7 +150,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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] type_ = pm_scope_class_and_type[1] @@ -162,7 +162,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): "video": self.video.to_dict(), "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()) == { "width", "height", @@ -183,10 +183,10 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): if "photo" in cls.__slots__: assert pm.photo == self.photo - assert cls.de_json(None, bot) is None - assert PaidMedia.de_json({}, bot) is None + assert cls.de_json(None, offline_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 = { "type": "invalid", "width": self.width, @@ -195,7 +195,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): "video": self.video.to_dict(), "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 == { "width": self.width, "height": self.height, @@ -207,7 +207,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): assert type(pm) is PaidMedia 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 TransactionPartnerPhoto instance.""" json_dict = { @@ -218,7 +218,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): "video": self.video.to_dict(), "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): pm_dict = paid_media.to_dict() @@ -238,7 +238,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): assert type(PaidMedia("video").type) is PaidMediaType assert PaidMedia("unknown").type == "unknown" - def test_equality(self, paid_media, bot): + def test_equality(self, paid_media, offline_bot): a = PaidMedia("base_type") b = PaidMedia("base_type") c = paid_media @@ -266,7 +266,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): if hasattr(c, "video"): json_dict = c.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 hash(c) != hash(f) @@ -274,7 +274,7 @@ class TestPaidMediaWithoutRequest(PaidMediaTestBase): if hasattr(c, "photo"): json_dict = c.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 hash(c) != hash(f) @@ -292,13 +292,13 @@ class TestPaidMediaInfoWithoutRequest(PaidMediaInfoTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "star_count": self.star_count, "paid_media": [t.to_dict() for t in self.paid_media], } - pmi = PaidMediaInfo.de_json(json_dict, bot) - pmi_none = PaidMediaInfo.de_json(None, bot) + pmi = PaidMediaInfo.de_json(json_dict, offline_bot) + pmi_none = PaidMediaInfo.de_json(None, offline_bot) assert pmi.paid_media == tuple(self.paid_media) assert pmi.star_count == self.star_count assert pmi_none is None diff --git a/tests/test_poll.py b/tests/test_poll.py index 81619a112..aedc5cf52 100644 --- a/tests/test_poll.py +++ b/tests/test_poll.py @@ -305,7 +305,7 @@ class PollTestBase: class TestPollWithoutRequest(PollTestBase): - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "question": self.question, @@ -321,7 +321,7 @@ class TestPollWithoutRequest(PollTestBase): "close_date": to_timestamp(self.close_date), "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.id == self.id_ @@ -343,7 +343,7 @@ class TestPollWithoutRequest(PollTestBase): assert to_timestamp(poll.close_date) == to_timestamp(self.close_date) 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 = { "id": self.id_, "question": self.question, @@ -361,7 +361,7 @@ class TestPollWithoutRequest(PollTestBase): } 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) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_proximityalerttriggered.py b/tests/test_proximityalerttriggered.py index de49b699f..6367af9d3 100644 --- a/tests/test_proximityalerttriggered.py +++ b/tests/test_proximityalerttriggered.py @@ -44,13 +44,13 @@ class TestProximityAlertTriggeredWithoutRequest(ProximityAlertTriggeredTestBase) assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "traveler": self.traveler.to_dict(), "watcher": self.watcher.to_dict(), "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.traveler == self.traveler diff --git a/tests/test_reaction.py b/tests/test_reaction.py index 67ece80e3..79f3e2c40 100644 --- a/tests/test_reaction.py +++ b/tests/test_reaction.py @@ -115,13 +115,13 @@ class TestReactionTypesWithoutRequest: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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__ - assert cls.de_json(None, bot) is None - assert ReactionType.de_json({}, bot) is None + assert cls.de_json(None, offline_bot) is None + assert ReactionType.de_json({}, offline_bot) is None 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 isinstance(const_reaction_type, ReactionType) @@ -131,9 +131,9 @@ class TestReactionTypesWithoutRequest: ): 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) - 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 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): 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"} - reaction_type = ReactionType.de_json(json_dict, bot) + reaction_type = ReactionType.de_json(json_dict, offline_bot) assert type(reaction_type) is ReactionType assert reaction_type.type == "invalid" - def test_de_json_subclass(self, reaction_type, bot, chat_id): - """This makes sure that e.g. ReactionTypeEmoji(data, bot) never returns a + def test_de_json_subclass(self, reaction_type, offline_bot, chat_id): + """This makes sure that e.g. ReactionTypeEmoji(data, offline_bot) never returns a ReactionTypeCustomEmoji instance.""" cls = reaction_type.__class__ 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): reaction_type_dict = reaction_type.to_dict() @@ -237,13 +237,13 @@ class TestReactionCountWithoutRequest: set(mro_slots(reaction_count)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "type": self.type.to_dict(), "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 isinstance(reaction_count, ReactionCount) @@ -252,7 +252,7 @@ class TestReactionCountWithoutRequest: assert reaction_count.type.emoji == self.type.emoji 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): reaction_count_dict = reaction_count.to_dict() diff --git a/tests/test_reply.py b/tests/test_reply.py index 5cacb7b6b..a450a721d 100644 --- a/tests/test_reply.py +++ b/tests/test_reply.py @@ -73,7 +73,7 @@ class TestExternalReplyInfoWithoutRequest(ExternalReplyInfoTestBase): set(mro_slots(external_reply_info)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "origin": self.origin.to_dict(), "chat": self.chat.to_dict(), @@ -83,7 +83,7 @@ class TestExternalReplyInfoWithoutRequest(ExternalReplyInfoTestBase): "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.origin == self.origin @@ -93,7 +93,7 @@ class TestExternalReplyInfoWithoutRequest(ExternalReplyInfoTestBase): assert external_reply_info.giveaway == self.giveaway 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): 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 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 = { "text": self.text, "position": self.position, @@ -159,7 +159,7 @@ class TestTextQuoteWithoutRequest(TextQuoteTestBase): "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.text == self.text @@ -167,7 +167,7 @@ class TestTextQuoteWithoutRequest(TextQuoteTestBase): assert text_quote.entities == tuple(self.entities) 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): text_quote_dict = text_quote.to_dict() @@ -233,7 +233,7 @@ class TestReplyParametersWithoutRequest(ReplyParametersTestBase): set(mro_slots(reply_parameters)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "message_id": self.message_id, "chat_id": self.chat_id, @@ -244,7 +244,7 @@ class TestReplyParametersWithoutRequest(ReplyParametersTestBase): "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.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_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): reply_parameters_dict = reply_parameters.to_dict() diff --git a/tests/test_sentwebappmessage.py b/tests/test_sentwebappmessage.py index e4bc116d0..bd206eede 100644 --- a/tests/test_sentwebappmessage.py +++ b/tests/test_sentwebappmessage.py @@ -45,7 +45,7 @@ class TestSentWebAppMessageWithoutRequest(SentWebAppMessageTestBase): assert isinstance(sent_web_app_message_dict, dict) 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} m = SentWebAppMessage.de_json(data, None) assert m.api_kwargs == {} diff --git a/tests/test_shared.py b/tests/test_shared.py index c51bcf5ea..9cc8d4bca 100644 --- a/tests/test_shared.py +++ b/tests/test_shared.py @@ -47,19 +47,19 @@ class TestUsersSharedWithoutRequest(UsersSharedTestBase): assert users_shared_dict["request_id"] == self.request_id 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 = { "request_id": self.request_id, "users": [user.to_dict() for user in self.users], "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.request_id == self.request_id 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): 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["chat_id"] == self.chat_id - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "request_id": self.request_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.request_id == self.request_id @@ -178,12 +178,12 @@ class TestSharedUserWithoutRequest(SharedUserTestBase): assert shared_user_dict["username"] == self.username 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 = { "user_id": self.user_id, "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.user_id == self.user_id @@ -192,7 +192,7 @@ class TestSharedUserWithoutRequest(SharedUserTestBase): assert shared_user.username is None assert shared_user.photo == () - def test_de_json_all(self, bot): + def test_de_json_all(self, offline_bot): json_dict = { "user_id": self.user_id, "first_name": self.first_name, @@ -200,7 +200,7 @@ class TestSharedUserWithoutRequest(SharedUserTestBase): "username": self.username, "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.user_id == self.user_id @@ -209,7 +209,7 @@ class TestSharedUserWithoutRequest(SharedUserTestBase): assert shared_user.username == self.username 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): a = SharedUser( diff --git a/tests/test_stars.py b/tests/test_stars.py index ef700ae39..23ddb4109 100644 --- a/tests/test_stars.py +++ b/tests/test_stars.py @@ -253,7 +253,7 @@ class TestStarTransactionWithoutRequest(StarTransactionTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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 = { "id": self.id, "amount": self.amount, @@ -261,8 +261,8 @@ class TestStarTransactionWithoutRequest(StarTransactionTestBase): "source": self.source.to_dict(), "receiver": self.receiver.to_dict(), } - st = StarTransaction.de_json(json_dict, bot) - st_none = StarTransaction.de_json(None, bot) + st = StarTransaction.de_json(json_dict, offline_bot) + st_none = StarTransaction.de_json(None, offline_bot) assert st.api_kwargs == {} assert st.id == self.id assert st.amount == self.amount @@ -271,10 +271,10 @@ class TestStarTransactionWithoutRequest(StarTransactionTestBase): assert st.receiver == self.receiver 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() 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) # 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 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 = { "transactions": [t.to_dict() for t in self.transactions], } - st = StarTransactions.de_json(json_dict, bot) - st_none = StarTransactions.de_json(None, bot) + st = StarTransactions.de_json(json_dict, offline_bot) + st_none = StarTransactions.de_json(None, offline_bot) assert st.api_kwargs == {} assert st.transactions == tuple(self.transactions) assert st_none is None @@ -390,7 +390,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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] type_ = tp_scope_class_and_type[1] @@ -400,7 +400,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase): "withdrawal_state": self.withdrawal_state.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( cls.__slots__ ) @@ -414,17 +414,17 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase): assert tp.user == self.user assert tp.invoice_payload == self.invoice_payload - assert cls.de_json(None, bot) is None - assert TransactionPartner.de_json({}, bot) is None + assert cls.de_json(None, offline_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 = { "type": "invalid", "invoice_payload": self.invoice_payload, "withdrawal_state": self.withdrawal_state.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 == { "withdrawal_state": self.withdrawal_state.to_dict(), "user": self.user.to_dict(), @@ -434,7 +434,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase): assert type(tp) is TransactionPartner 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 TransactionPartnerFragment instance.""" json_dict = { @@ -443,7 +443,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase): "withdrawal_state": self.withdrawal_state.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): tp_dict = transaction_partner.to_dict() @@ -460,7 +460,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase): assert type(TransactionPartner("other").type) is TransactionPartnerType assert TransactionPartner("unknown").type == "unknown" - def test_equality(self, transaction_partner, bot): + def test_equality(self, transaction_partner, offline_bot): a = TransactionPartner("base_type") b = TransactionPartner("base_type") c = transaction_partner @@ -488,7 +488,7 @@ class TestTransactionPartnerWithoutRequest(TransactionPartnerTestBase): if hasattr(c, "user"): json_dict = c.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 hash(c) != hash(f) @@ -506,7 +506,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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] type_ = rws_scope_class_and_type[1] @@ -515,7 +515,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): "date": to_timestamp(self.date), "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 isinstance(rws, RevenueWithdrawalState) @@ -526,16 +526,16 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): if "url" in cls.__slots__: assert rws.url == self.url - assert cls.de_json(None, bot) is None - assert RevenueWithdrawalState.de_json({}, bot) is None + assert cls.de_json(None, offline_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 = { "type": "invalid", "date": to_timestamp(self.date), "url": self.url, } - rws = RevenueWithdrawalState.de_json(json_dict, bot) + rws = RevenueWithdrawalState.de_json(json_dict, offline_bot) assert rws.api_kwargs == { "date": to_timestamp(self.date), "url": self.url, @@ -544,7 +544,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): assert type(rws) is RevenueWithdrawalState 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 RevenueWithdrawalStateFailed instance.""" json_dict = { @@ -552,7 +552,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): "date": to_timestamp(self.date), "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): rws_dict = revenue_withdrawal_state.to_dict() @@ -568,7 +568,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): assert type(RevenueWithdrawalState("failed").type) is RevenueWithdrawalStateType 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") b = RevenueWithdrawalState("base_type") c = revenue_withdrawal_state @@ -596,7 +596,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): if hasattr(c, "url"): json_dict = c.to_dict() 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 hash(c) == hash(f) @@ -604,7 +604,7 @@ class TestRevenueWithdrawalStateWithoutRequest(RevenueWithdrawalStateTestBase): if hasattr(c, "date"): json_dict = c.to_dict() 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 hash(c) != hash(f) diff --git a/tests/test_story.py b/tests/test_story.py index 1aad292cb..190c4ec13 100644 --- a/tests/test_story.py +++ b/tests/test_story.py @@ -38,14 +38,14 @@ class TestStoryWithoutRequest(StoryTestBase): assert getattr(story, attr, "err") != "err", f"got extra slot '{attr}'" 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} - story = Story.de_json(json_dict, bot) + story = Story.de_json(json_dict, offline_bot) assert story.api_kwargs == {} assert story.chat == self.chat assert story.id == self.id 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): story_dict = story.to_dict() diff --git a/tests/test_update.py b/tests/test_update.py index 46619fbfd..f2e9dbf61 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -227,11 +227,11 @@ class TestUpdateWithoutRequest(UpdateTestBase): assert len(mro_slots(update)) == len(set(mro_slots(update))), "duplicate slot" @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} # 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()}) - update = Update.de_json(json_dict, bot) + update = Update.de_json(json_dict, offline_bot) assert update.api_kwargs == {} assert update.update_id == self.update_id @@ -244,8 +244,8 @@ class TestUpdateWithoutRequest(UpdateTestBase): assert getattr(update, _type) == paramdict[_type] assert i == 1 - def test_update_de_json_empty(self, bot): - update = Update.de_json(None, bot) + def test_update_de_json_empty(self, offline_bot): + update = Update.de_json(None, offline_bot) assert update is None diff --git a/tests/test_user.py b/tests/test_user.py index 073d0af58..d8a6265f0 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -91,8 +91,8 @@ class TestUserWithoutRequest(UserTestBase): assert getattr(user, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(user)) == len(set(mro_slots(user))), "duplicate slot" - def test_de_json(self, json_dict, bot): - user = User.de_json(json_dict, bot) + def test_de_json(self, json_dict, offline_bot): + user = User.de_json(json_dict, offline_bot) assert user.api_kwargs == {} assert user.id == self.id_ diff --git a/tests/test_userprofilephotos.py b/tests/test_userprofilephotos.py index f0017ce6c..5ae686fad 100644 --- a/tests/test_userprofilephotos.py +++ b/tests/test_userprofilephotos.py @@ -41,9 +41,9 @@ class TestUserProfilePhotosWithoutRequest(UserProfilePhotosTestBase): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" 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]} - 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.total_count == self.total_count assert user_profile_photos.photos == tuple(tuple(p) for p in self.photos) diff --git a/tests/test_videochat.py b/tests/test_videochat.py index 5fbdf8ba8..e5de669c6 100644 --- a/tests/test_videochat.py +++ b/tests/test_videochat.py @@ -105,9 +105,9 @@ class TestVideoChatParticipantsInvitedWithoutRequest: assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'" 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()]} - 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 isinstance(video_chat_participants.users, tuple) @@ -161,20 +161,20 @@ class TestVideoChatScheduledWithoutRequest: def test_expected_values(self): assert VideoChatScheduled(self.start_date).start_date == self.start_date - def test_de_json(self, bot): - assert VideoChatScheduled.de_json({}, bot=bot) is None + def test_de_json(self, offline_bot): + assert VideoChatScheduled.de_json({}, bot=offline_bot) is None 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 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)} 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) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_webappdata.py b/tests/test_webappdata.py index a13043042..ba8d43608 100644 --- a/tests/test_webappdata.py +++ b/tests/test_webappdata.py @@ -46,9 +46,9 @@ class TestWebAppDataWithoutRequest(WebAppDataTestBase): assert web_app_data_dict["data"] == self.data 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} - 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.data == self.data diff --git a/tests/test_webappinfo.py b/tests/test_webappinfo.py index 40d658733..76dd018d5 100644 --- a/tests/test_webappinfo.py +++ b/tests/test_webappinfo.py @@ -44,9 +44,9 @@ class TestWebAppInfoWithoutRequest(WebAppInfoTestBase): assert isinstance(web_app_info_dict, dict) 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} - 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.url == self.url diff --git a/tests/test_webhookinfo.py b/tests/test_webhookinfo.py index 48bb5ee38..cfd6810b1 100644 --- a/tests/test_webhookinfo.py +++ b/tests/test_webhookinfo.py @@ -72,7 +72,7 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase): == self.last_synchronization_error_date ) - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "url": self.url, "has_custom_certificate": self.has_custom_certificate, @@ -83,7 +83,7 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase): "ip_address": self.ip_address, "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.url == self.url @@ -99,10 +99,10 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase): self.last_synchronization_error_date ) - none = WebhookInfo.de_json(None, bot) + none = WebhookInfo.de_json(None, offline_bot) 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 = { "url": self.url, "has_custom_certificate": self.has_custom_certificate, @@ -113,7 +113,7 @@ class TestWebhookInfoWithoutRequest(WebhookInfoTestBase): "ip_address": self.ip_address, "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_tz = WebhookInfo.de_json(json_dict, tz_bot)