async def animation(bot, chat_id):
    with data_file("game.gif").open("rb") as f:
        thumb = data_file("thumb.jpg")
        return (await bot.send_animation(chat_id,
                                         animation=f,
                                         read_timeout=50,
                                         thumb=thumb.open("rb"))).animation
Пример #2
0
    def test_from_input_input_media(self):
        input_media_no_thumb = InputMediaPhoto(
            media=data_file("telegram.jpg").read_bytes())
        input_media_thumb = InputMediaVideo(
            media=data_file("telegram.mp4").read_bytes(),
            thumb=data_file("telegram.jpg").read_bytes(),
        )

        request_parameter = RequestParameter.from_input(
            "key", input_media_no_thumb)
        expected_no_thumb = input_media_no_thumb.to_dict()
        expected_no_thumb.update(
            {"media": input_media_no_thumb.media.attach_uri})
        assert request_parameter.value == expected_no_thumb
        assert request_parameter.input_files == [input_media_no_thumb.media]

        request_parameter = RequestParameter.from_input(
            "key", input_media_thumb)
        expected_thumb = input_media_thumb.to_dict()
        expected_thumb.update({"media": input_media_thumb.media.attach_uri})
        expected_thumb.update({"thumb": input_media_thumb.thumb.attach_uri})
        assert request_parameter.value == expected_thumb
        assert request_parameter.input_files == [
            input_media_thumb.media, input_media_thumb.thumb
        ]

        request_parameter = RequestParameter.from_input(
            "key", [input_media_thumb, input_media_no_thumb])
        assert request_parameter.value == [expected_thumb, expected_no_thumb]
        assert request_parameter.input_files == [
            input_media_thumb.media,
            input_media_thumb.thumb,
            input_media_no_thumb.media,
        ]
Пример #3
0
 def test_with_local_files(self):
     input_media_animation = InputMediaAnimation(
         data_file("telegram.mp4"), thumb=data_file("telegram.jpg"))
     assert input_media_animation.media == data_file(
         "telegram.mp4").as_uri()
     assert input_media_animation.thumb == data_file(
         "telegram.jpg").as_uri()
    def test_mimetypes(self, caplog):
        # Only test a few to make sure logic works okay
        assert InputFile(
            data_file("telegram.jpg").open("rb")).mimetype == "image/jpeg"
        # For some reason python can guess the type on macOS
        assert InputFile(data_file("telegram.webp").open("rb")).mimetype in [
            "application/octet-stream",
            "image/webp",
        ]
        assert InputFile(
            data_file("telegram.mp3").open("rb")).mimetype == "audio/mpeg"
        # For some reason windows drops the trailing i
        assert InputFile(data_file("telegram.midi").open("rb")).mimetype in [
            "audio/mid",
            "audio/midi",
        ]

        # Test guess from file
        assert InputFile(BytesIO(b"blah"),
                         filename="tg.jpg").mimetype == "image/jpeg"
        assert InputFile(BytesIO(b"blah"),
                         filename="tg.mp3").mimetype == "audio/mpeg"

        # Test fallback
        assert (InputFile(
            BytesIO(b"blah"),
            filename="tg.notaproperext").mimetype == "application/octet-stream"
                )
        assert InputFile(
            BytesIO(b"blah")).mimetype == "application/octet-stream"

        # Test string file
        assert InputFile(
            data_file("text_file.txt").open()).mimetype == "text/plain"
    async def test_max_caption_length(self, bot, chat_id):
        good_caption = "a" * constants.MessageLimit.CAPTION_LENGTH
        with data_file("telegram.png").open("rb") as f:
            good_msg = await bot.send_photo(photo=f, caption=good_caption, chat_id=chat_id)
        assert good_msg.caption == good_caption

        bad_caption = good_caption + "Z"
        match = "Media_caption_too_long"
        with pytest.raises(BadRequest, match=match), data_file("telegram.png").open("rb") as f:
            await bot.send_photo(photo=f, caption=bad_caption, chat_id=chat_id)
Пример #6
0
 def test_from_input_inputmedia_without_attach(self):
     """This case will never happen, but we test it for completeness"""
     input_media = InputMediaVideo(
         data_file("telegram.png").read_bytes(),
         thumb=data_file("telegram.png").read_bytes(),
         parse_mode=None,
     )
     input_media.media.attach_name = None
     input_media.thumb.attach_name = None
     request_parameter = RequestParameter.from_input("key", input_media)
     assert request_parameter.value == {"type": "video"}
     assert request_parameter.input_files == [
         input_media.media, input_media.thumb
     ]
    def test_parse_file_input_attach(self, attach):
        source_file = data_file("text_file.txt")
        parsed = telegram._utils.files.parse_file_input(
            source_file.read_bytes(), attach=attach)

        assert isinstance(parsed, InputFile)
        assert bool(parsed.attach_name) is attach
    async def test_create_new_sticker_set_local_files(self, monkeypatch, bot,
                                                      chat_id):
        # 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()

        async def make_assertion(_, data, *args, **kwargs):
            nonlocal test_flag
            test_flag = (data.get("png_sticker") == expected
                         and data.get("tgs_sticker") == expected
                         and data.get("webm_sticker") == expected)

        monkeypatch.setattr(bot, "_post", make_assertion)
        await bot.create_new_sticker_set(
            chat_id,
            "name",
            "title",
            "emoji",
            png_sticker=file,
            tgs_sticker=file,
            webm_sticker=file,
        )
        assert test_flag
        monkeypatch.delattr(bot, "_post")
 async def test_bot_methods_1_webm(self, bot, chat_id):
     with data_file("telegram_video_sticker.webm").open("rb") as f:
         assert await bot.add_sticker_to_set(
             chat_id,
             f"video_test_by_{bot.username}",
             webm_sticker=f,
             emojis="🤔")
 async def test_bot_methods_1_tgs(self, bot, chat_id):
     assert await bot.add_sticker_to_set(
         chat_id,
         f"animated_test_by_{bot.username}",
         tgs_sticker=data_file("telegram_animated_sticker.tgs").open("rb"),
         emojis="😄",
     )
Пример #11
0
def local_file(bot):
    return File(
        TestFile.file_id,
        TestFile.file_unique_id,
        file_path=str(data_file("local_file.txt")),
        file_size=TestFile.file_size,
        bot=bot,
    )
Пример #12
0
 async def func():
     return await bot.send_media_group(
         chat_id,
         [
             InputMediaVideo(video_file),
             InputMediaPhoto(photo_file),
             InputMediaPhoto(data_file("telegram.jpg").read_bytes()),
         ],
     )
    async def test_send_string(self, bot, chat_id):
        # We test this here and not at the respective test modules because it's not worth
        # duplicating the test for the different methods
        message = await bot.send_document(
            chat_id,
            InputFile(data_file("text_file.txt").read_text(encoding="utf-8")))
        out = BytesIO()

        assert await (await message.document.get_file()).download(out=out)
        out.seek(0)

        assert out.read().decode("utf-8") == "PTB Rocks! ⅞"
    def test_parse_file_input_bytes(self):
        source_file = data_file("text_file.txt")
        parsed = telegram._utils.files.parse_file_input(
            source_file.read_bytes())

        assert isinstance(parsed, InputFile)
        assert parsed.filename == "application.octet-stream"

        parsed = telegram._utils.files.parse_file_input(
            source_file.read_bytes(), filename="test_file")

        assert isinstance(parsed, InputFile)
        assert parsed.filename == "test_file"
    async def test_send_video_local_files(self, monkeypatch, bot, chat_id):
        # 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()

        async def make_assertion(_, data, *args, **kwargs):
            nonlocal test_flag
            test_flag = data.get("video") == expected and data.get("thumb") == expected

        monkeypatch.setattr(bot, "_post", make_assertion)
        await bot.send_video(chat_id, file, thumb=file)
        assert test_flag
    def test_parse_file_input_file_like(self):
        source_file = data_file("game.gif")
        with source_file.open("rb") as file:
            parsed = telegram._utils.files.parse_file_input(file)

        assert isinstance(parsed, InputFile)
        assert parsed.filename == "game.gif"

        with source_file.open("rb") as file:
            parsed = telegram._utils.files.parse_file_input(
                file, filename="test_file")

        assert isinstance(parsed, InputFile)
        assert parsed.filename == "test_file"
    async def test_upload_sticker_file_local_files(self, monkeypatch, bot,
                                                   chat_id):
        # 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()

        async def make_assertion(_, data, *args, **kwargs):
            nonlocal test_flag
            test_flag = data.get("png_sticker") == expected

        monkeypatch.setattr(bot, "_post", make_assertion)
        await bot.upload_sticker_file(chat_id, file)
        assert test_flag
        monkeypatch.delattr(bot, "_post")
 async def test_bot_methods_1_png(self, bot, chat_id, sticker_file):
     with data_file("telegram_sticker.png").open("rb") as f:
         # chat_id was hardcoded as 95205500 but it stopped working for some reason
         file = await bot.upload_sticker_file(chat_id, f)
     assert file
     assert await bot.add_sticker_to_set(chat_id,
                                         f"test_by_{bot.username}",
                                         png_sticker=file.file_id,
                                         emojis="😄")
     # Also test with file input and mask
     assert await bot.add_sticker_to_set(
         chat_id,
         f"test_by_{bot.username}",
         png_sticker=sticker_file,
         emojis="😄",
         mask_position=MaskPosition(MaskPosition.EYES, -1, 1, 2),
     )
Пример #19
0
def input_media_photo() -> InputMediaPhoto:
    return InputMediaPhoto(
        media=data_file("telegram.jpg").read_bytes(),
        parse_mode=None,
    )
Пример #20
0
def input_media_video() -> InputMediaVideo:
    return InputMediaVideo(
        media=data_file("telegram.mp4").read_bytes(),
        thumb=data_file("telegram.jpg").read_bytes(),
        parse_mode=None,
    )
Пример #21
0
 def test_with_local_files(self):
     input_media_document = InputMediaDocument(
         data_file("telegram.mp4"), thumb=data_file("telegram.jpg"))
     assert input_media_document.media == data_file("telegram.mp4").as_uri()
     assert input_media_document.thumb == data_file("telegram.jpg").as_uri()
Пример #22
0
 def test_with_local_files(self):
     input_media_audio = InputMediaAudio(data_file("telegram.mp4"),
                                         thumb=data_file("telegram.jpg"))
     assert input_media_audio.media == data_file("telegram.mp4").as_uri()
     assert input_media_audio.thumb == data_file("telegram.jpg").as_uri()
Пример #23
0
 def test_with_local_files(self):
     input_media_photo = InputMediaPhoto(data_file("telegram.mp4"))
     assert input_media_photo.media == data_file("telegram.mp4").as_uri()
def animation_file():
    f = data_file("game.gif").open("rb")
    yield f
    f.close()
    async def test_start_webhook_parameters_passing(self, updater,
                                                    monkeypatch):
        expected_delete_webhook = dict(drop_pending_updates=None, )

        expected_set_webhook = dict(
            certificate=None,
            max_connections=40,
            allowed_updates=None,
            ip_address=None,
            secret_token=None,
            **expected_delete_webhook,
        )

        async def set_webhook(*args, **kwargs):
            for key, value in expected_set_webhook.items():
                assert kwargs.pop(key, None) == value, f"set, {key}, {value}"

            assert kwargs in (
                {
                    "url": "http://127.0.0.1:80/"
                },
                {
                    "url": "http://listen:80/"
                },
                {
                    "url": "https://listen-ssl:42/ssl-path"
                },
            )
            return True

        async def delete_webhook(*args, **kwargs):
            for key, value in expected_delete_webhook.items():
                assert kwargs.pop(key,
                                  None) == value, f"delete, {key}, {value}"

            assert kwargs == {}
            return True

        async def serve_forever(*args, **kwargs):
            kwargs.get("ready").set()

        monkeypatch.setattr(updater.bot, "set_webhook", set_webhook)
        monkeypatch.setattr(updater.bot, "delete_webhook", delete_webhook)
        monkeypatch.setattr(WebhookServer, "serve_forever", serve_forever)

        async with updater:
            await updater.start_webhook()
            await updater.stop()
            expected_delete_webhook = dict(
                drop_pending_updates=True,
                api_kwargs=None,
            )

            expected_set_webhook = dict(
                certificate=data_file("sslcert.pem").read_bytes(),
                max_connections=47,
                allowed_updates=["message"],
                ip_address="123.456.789",
                secret_token=None,
                **expected_delete_webhook,
            )

            await updater.start_webhook(
                listen="listen",
                allowed_updates=["message"],
                drop_pending_updates=True,
                ip_address="123.456.789",
                max_connections=47,
                cert=str(data_file("sslcert.pem").resolve()),
            )
            await updater.stop()

            await updater.start_webhook(
                listen="listen-ssl",
                port=42,
                url_path="ssl-path",
                allowed_updates=["message"],
                drop_pending_updates=True,
                ip_address="123.456.789",
                max_connections=47,
                cert=data_file("sslcert.pem"),
                key=data_file("sslcert.key"),
            )
            await updater.stop()
def document_file():
    f = data_file("telegram.png").open("rb")
    yield f
    f.close()
def video_note_file():
    f = data_file("telegram2.mp4").open("rb")
    yield f
    f.close()
async def document(bot, chat_id):
    with data_file("telegram.png").open("rb") as f:
        return (await bot.send_document(chat_id, document=f, read_timeout=50)).document
async def video_note(bot, chat_id):
    with data_file("telegram2.mp4").open("rb") as f:
        return (await bot.send_video_note(chat_id,
                                          video_note=f,
                                          read_timeout=50)).video_note
def chatphoto_file():
    f = data_file("telegram.jpg").open("rb")
    yield f
    f.close()