diff --git a/tests/conftest.py b/tests/conftest.py index 33b837bca..b86e678ef 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,6 +23,7 @@ import inspect import os import re from collections import defaultdict +from pathlib import Path from queue import Queue from threading import Thread, Event from time import sleep @@ -217,16 +218,24 @@ def updater(bot): up.stop() +PROJECT_ROOT_PATH = Path(__file__).parent.parent.resolve() +TEST_DATA_PATH = Path(__file__).parent.resolve() / "data" + + +def data_file(filename: str): + return TEST_DATA_PATH / filename + + @pytest.fixture(scope='function') def thumb_file(): - f = open('tests/data/thumb.jpg', 'rb') + f = data_file('thumb.jpg').open('rb') yield f f.close() @pytest.fixture(scope='class') def class_thumb_file(): - f = open('tests/data/thumb.jpg', 'rb') + f = data_file('thumb.jpg').open('rb') yield f f.close() diff --git a/tests/test_animation.py b/tests/test_animation.py index 89d3136c9..6b8c00480 100644 --- a/tests/test_animation.py +++ b/tests/test_animation.py @@ -25,21 +25,27 @@ from flaky import flaky from telegram import PhotoSize, Animation, Voice, MessageEntity, Bot from telegram.error import BadRequest, TelegramError from telegram.helpers import escape_markdown -from tests.conftest import check_shortcut_call, check_shortcut_signature, check_defaults_handling +from tests.conftest import ( + check_shortcut_call, + check_shortcut_signature, + check_defaults_handling, + data_file, +) @pytest.fixture(scope='function') def animation_file(): - f = Path('tests/data/game.gif').open('rb') + f = data_file('game.gif').open('rb') yield f f.close() @pytest.fixture(scope='class') def animation(bot, chat_id): - with Path('tests/data/game.gif').open('rb') as f: + with data_file('game.gif').open('rb') as f: + thumb = data_file('thumb.jpg') return bot.send_animation( - chat_id, animation=f, timeout=50, thumb=open('tests/data/thumb.jpg', 'rb') + chat_id, animation=f, timeout=50, thumb=thumb.open('rb') ).animation @@ -193,8 +199,8 @@ class TestAnimation: def test_send_animation_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag diff --git a/tests/test_audio.py b/tests/test_audio.py index 5c55c722e..3455317cf 100644 --- a/tests/test_audio.py +++ b/tests/test_audio.py @@ -25,22 +25,26 @@ from flaky import flaky from telegram import Audio, Voice, MessageEntity, Bot from telegram.error import TelegramError from telegram.helpers import escape_markdown -from tests.conftest import check_shortcut_call, check_shortcut_signature, check_defaults_handling +from tests.conftest import ( + check_shortcut_call, + check_shortcut_signature, + check_defaults_handling, + data_file, +) @pytest.fixture(scope='function') def audio_file(): - f = Path('tests/data/telegram.mp3').open('rb') + f = data_file('telegram.mp3').open('rb') yield f f.close() @pytest.fixture(scope='class') def audio(bot, chat_id): - with Path('tests/data/telegram.mp3').open('rb') as f: - return bot.send_audio( - chat_id, audio=f, timeout=50, thumb=Path('tests/data/thumb.jpg').open('rb') - ).audio + with data_file('telegram.mp3').open('rb') as f: + thumb = data_file('thumb.jpg') + return bot.send_audio(chat_id, audio=f, timeout=50, thumb=thumb.open('rb')).audio class TestAudio: @@ -215,8 +219,8 @@ class TestAudio: def test_send_audio_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag diff --git a/tests/test_bot.py b/tests/test_bot.py index 9c2b0c864..669c5c8f6 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -21,7 +21,6 @@ import logging import time import datetime as dtm from collections import defaultdict -from pathlib import Path from platform import python_implementation import pytest @@ -59,9 +58,15 @@ from telegram.constants import MAX_INLINE_QUERY_RESULTS from telegram.ext import ExtBot, InvalidCallbackData from telegram.error import BadRequest, InvalidToken, NetworkError, RetryAfter, TelegramError from telegram._utils.datetime import from_timestamp, to_timestamp -from telegram.helpers import escape_markdown from telegram._utils.defaultvalue import DefaultValue -from tests.conftest import expect_bad_request, check_defaults_handling, GITHUB_ACTION, build_kwargs +from telegram.helpers import escape_markdown +from tests.conftest import ( + expect_bad_request, + check_defaults_handling, + GITHUB_ACTION, + build_kwargs, + data_file, +) from tests.bots import FALLBACKS @@ -99,7 +104,7 @@ def message(bot, chat_id): @pytest.fixture(scope='class') def media_message(bot, chat_id): - with Path('tests/data/telegram.ogg').open('rb') as f: + with data_file('telegram.ogg').open('rb') as f: return bot.send_voice(chat_id, voice=f, caption='my caption', timeout=10) @@ -1039,7 +1044,7 @@ class TestBot: # get_file is tested multiple times in the test_*media* modules. # Here we only test the behaviour for bot apis in local mode def test_get_file_local_mode(self, bot, monkeypatch): - path = str(Path.cwd() / 'tests' / 'data' / 'game.gif') + path = str(data_file('game.gif')) def _post(*args, **kwargs): return { @@ -1924,14 +1929,14 @@ class TestBot: def func(): assert bot.set_chat_photo(channel_id, f) - with Path('tests/data/telegram_test_channel.jpg').open('rb') as f: + with data_file('telegram_test_channel.jpg').open('rb') as f: expect_bad_request(func, 'Type of file mismatch', 'Telegram did not accept the file.') def test_set_chat_photo_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag @@ -2008,7 +2013,7 @@ class TestBot: # Test file uploading with pytest.raises(OkException): - bot.send_photo(chat_id, open('tests/data/telegram.jpg', 'rb'), timeout=TIMEOUT) + bot.send_photo(chat_id, data_file('telegram.jpg').open('rb'), timeout=TIMEOUT) # Test JSON submission with pytest.raises(OkException): @@ -2032,7 +2037,7 @@ class TestBot: # Test file uploading with pytest.raises(OkException): - bot.send_photo(chat_id, open('tests/data/telegram.jpg', 'rb')) + bot.send_photo(chat_id, data_file('telegram.jpg').open('rb')) @flaky(3, 1) def test_send_message_entities(self, bot, chat_id): diff --git a/tests/test_chatphoto.py b/tests/test_chatphoto.py index f76445ee4..0142d77b4 100644 --- a/tests/test_chatphoto.py +++ b/tests/test_chatphoto.py @@ -29,12 +29,13 @@ from tests.conftest import ( check_shortcut_call, check_shortcut_signature, check_defaults_handling, + data_file, ) @pytest.fixture(scope='function') def chatphoto_file(): - f = open('tests/data/telegram.jpg', 'rb') + f = data_file('telegram.jpg').open('rb') yield f f.close() @@ -68,23 +69,24 @@ class TestChatPhoto: @flaky(3, 1) def test_get_and_download(self, bot, chat_photo): + jpg_file = Path('telegram.jpg') new_file = bot.get_file(chat_photo.small_file_id) assert new_file.file_id == chat_photo.small_file_id assert new_file.file_path.startswith('https://') - new_file.download('telegram.jpg') + new_file.download(jpg_file) - assert Path('telegram.jpg').is_file() + assert jpg_file.is_file() new_file = bot.get_file(chat_photo.big_file_id) assert new_file.file_id == chat_photo.big_file_id assert new_file.file_path.startswith('https://') - new_file.download('telegram.jpg') + new_file.download(jpg_file) - assert Path('telegram.jpg').is_file() + assert jpg_file.is_file() def test_send_with_chat_photo(self, monkeypatch, bot, super_group_id, chat_photo): def test(url, data, **kwargs): diff --git a/tests/test_constants.py b/tests/test_constants.py index 17569a4f2..7b460f1d1 100644 --- a/tests/test_constants.py +++ b/tests/test_constants.py @@ -16,13 +16,12 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. -from pathlib import Path - import pytest from flaky import flaky from telegram import constants from telegram.error import BadRequest +from tests.conftest import data_file class TestConstants: @@ -39,13 +38,11 @@ class TestConstants: @flaky(3, 1) def test_max_caption_length(self, bot, chat_id): good_caption = 'a' * constants.MAX_CAPTION_LENGTH - with Path('tests/data/telegram.png').open('rb') as f: + with data_file('telegram.png').open('rb') as f: good_msg = bot.send_photo(photo=f, caption=good_caption, chat_id=chat_id) assert good_msg.caption == good_caption bad_caption = good_caption + 'Z' - with pytest.raises( - BadRequest, - match="Media_caption_too_long", - ), open('tests/data/telegram.png', 'rb') as f: + match = "Media_caption_too_long" + with pytest.raises(BadRequest, match=match), data_file('telegram.png').open('rb') as f: bot.send_photo(photo=f, caption=bad_caption, chat_id=chat_id) diff --git a/tests/test_document.py b/tests/test_document.py index 5474af603..f5f54bd4f 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -25,19 +25,24 @@ from flaky import flaky from telegram import Document, PhotoSize, Voice, MessageEntity, Bot from telegram.error import BadRequest, TelegramError from telegram.helpers import escape_markdown -from tests.conftest import check_shortcut_signature, check_shortcut_call, check_defaults_handling +from tests.conftest import ( + check_shortcut_signature, + check_shortcut_call, + check_defaults_handling, + data_file, +) @pytest.fixture(scope='function') def document_file(): - f = open('tests/data/telegram.png', 'rb') + f = data_file('telegram.png').open('rb') yield f f.close() @pytest.fixture(scope='class') def document(bot, chat_id): - with Path('tests/data/telegram.png').open('rb') as f: + with data_file('telegram.png').open('rb') as f: return bot.send_document(chat_id, document=f, timeout=50).document @@ -239,8 +244,8 @@ class TestDocument: def test_send_document_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag diff --git a/tests/test_file.py b/tests/test_file.py index 7f12df1e3..e423f2984 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -25,6 +25,7 @@ from flaky import flaky from telegram import File, Voice from telegram.error import TelegramError +from tests.conftest import data_file @pytest.fixture(scope='class') @@ -43,7 +44,7 @@ def local_file(bot): return File( TestFile.file_id, TestFile.file_unique_id, - file_path=str(Path.cwd() / 'tests' / 'data' / 'local_file.txt'), + file_path=str(data_file('local_file.txt')), file_size=TestFile.file_size, bot=bot, ) diff --git a/tests/test_files.py b/tests/test_files.py index 0973c88c5..6441cd804 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -16,25 +16,25 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. -from pathlib import Path import pytest import telegram._utils.datetime import telegram._utils.files from telegram import InputFile, Animation, MessageEntity +from tests.conftest import TEST_DATA_PATH, data_file class TestFiles: @pytest.mark.parametrize( 'string,expected', [ - ('tests/data/game.gif', True), - ('tests/data', False), - (str(Path.cwd() / 'tests' / 'data' / 'game.gif'), True), - (str(Path.cwd() / 'tests' / 'data'), False), - (Path.cwd() / 'tests' / 'data' / 'game.gif', True), - (Path.cwd() / 'tests' / 'data', False), + (str(data_file('game.gif')), True), + (str(TEST_DATA_PATH), False), + (str(data_file('game.gif')), True), + (str(TEST_DATA_PATH), False), + (data_file('game.gif'), True), + (TEST_DATA_PATH, False), ('https:/api.org/file/botTOKEN/document/file_3', False), (None, False), ], @@ -45,19 +45,13 @@ class TestFiles: @pytest.mark.parametrize( 'string,expected', [ - ('tests/data/game.gif', (Path.cwd() / 'tests' / 'data' / 'game.gif').as_uri()), - ('tests/data', 'tests/data'), + (data_file('game.gif'), data_file('game.gif').as_uri()), + (TEST_DATA_PATH, TEST_DATA_PATH), ('file://foobar', 'file://foobar'), - ( - str(Path.cwd() / 'tests' / 'data' / 'game.gif'), - (Path.cwd() / 'tests' / 'data' / 'game.gif').as_uri(), - ), - (str(Path.cwd() / 'tests' / 'data'), str(Path.cwd() / 'tests' / 'data')), - ( - Path.cwd() / 'tests' / 'data' / 'game.gif', - (Path.cwd() / 'tests' / 'data' / 'game.gif').as_uri(), - ), - (Path.cwd() / 'tests' / 'data', Path.cwd() / 'tests' / 'data'), + (str(data_file('game.gif')), data_file('game.gif').as_uri()), + (str(TEST_DATA_PATH), str(TEST_DATA_PATH)), + (data_file('game.gif'), data_file('game.gif').as_uri()), + (TEST_DATA_PATH, TEST_DATA_PATH), ( 'https:/api.org/file/botTOKEN/document/file_3', 'https:/api.org/file/botTOKEN/document/file_3', @@ -68,7 +62,7 @@ class TestFiles: assert telegram._utils.files.parse_file_input(string) == expected def test_parse_file_input_file_like(self): - source_file = Path('tests/data/game.gif') + source_file = data_file('game.gif') with source_file.open('rb') as file: parsed = telegram._utils.files.parse_file_input(file) @@ -86,7 +80,7 @@ class TestFiles: assert parsed.filename == 'test_file' def test_parse_file_input_bytes(self): - source_file = Path('tests/data/text_file.txt') + source_file = data_file('text_file.txt') parsed = telegram._utils.files.parse_file_input(source_file.read_bytes()) assert isinstance(parsed, InputFile) diff --git a/tests/test_inputfile.py b/tests/test_inputfile.py index 2f1e50487..84ae4c3da 100644 --- a/tests/test_inputfile.py +++ b/tests/test_inputfile.py @@ -20,27 +20,32 @@ import logging import subprocess import sys from io import BytesIO -from pathlib import Path + +import pytest from telegram import InputFile +from tests.conftest import data_file + + +@pytest.fixture(scope='class') +def png_file(): + return data_file('game.png') class TestInputFile: - png = Path('tests/data/game.png') - def test_slot_behaviour(self, mro_slots): inst = InputFile(BytesIO(b'blah'), filename='tg.jpg') 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" - def test_subprocess_pipe(self): + def test_subprocess_pipe(self, png_file): cmd_str = 'type' if sys.platform == 'win32' else 'cat' - cmd = [cmd_str, str(self.png)] + cmd = [cmd_str, str(png_file)] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=(sys.platform == 'win32')) in_file = InputFile(proc.stdout) - assert in_file.input_file_content == self.png.read_bytes() + assert in_file.input_file_content == png_file.read_bytes() assert in_file.mimetype == 'image/png' assert in_file.filename == 'image.png' @@ -53,9 +58,9 @@ class TestInputFile: def test_mimetypes(self, caplog): # Only test a few to make sure logic works okay - assert InputFile(open('tests/data/telegram.jpg', 'rb')).mimetype == 'image/jpeg' - assert InputFile(open('tests/data/telegram.webp', 'rb')).mimetype == 'image/webp' - assert InputFile(open('tests/data/telegram.mp3', 'rb')).mimetype == 'audio/mpeg' + assert InputFile(data_file('telegram.jpg').open('rb')).mimetype == 'image/jpeg' + assert InputFile(data_file('telegram.webp').open('rb')).mimetype == 'image/webp' + assert InputFile(data_file('telegram.mp3').open('rb')).mimetype == 'audio/mpeg' # Test guess from file assert InputFile(BytesIO(b'blah'), filename='tg.jpg').mimetype == 'image/jpeg' @@ -70,61 +75,61 @@ class TestInputFile: # Test string file with caplog.at_level(logging.DEBUG): - assert InputFile(open('tests/data/text_file.txt')).mimetype == 'text/plain' + assert InputFile(data_file('text_file.txt').open()).mimetype == 'text/plain' assert len(caplog.records) == 1 assert caplog.records[0].getMessage().startswith('Could not parse file content') def test_filenames(self): - assert InputFile(open('tests/data/telegram.jpg', 'rb')).filename == 'telegram.jpg' - assert InputFile(open('tests/data/telegram.jpg', 'rb'), filename='blah').filename == 'blah' + assert InputFile(data_file('telegram.jpg').open('rb')).filename == 'telegram.jpg' + assert InputFile(data_file('telegram.jpg').open('rb'), filename='blah').filename == 'blah' assert ( - InputFile(open('tests/data/telegram.jpg', 'rb'), filename='blah.jpg').filename + InputFile(data_file('telegram.jpg').open('rb'), filename='blah.jpg').filename == 'blah.jpg' ) - assert InputFile(open('tests/data/telegram', 'rb')).filename == 'telegram' - assert InputFile(open('tests/data/telegram', 'rb'), filename='blah').filename == 'blah' + assert InputFile(data_file('telegram').open('rb')).filename == 'telegram' + assert InputFile(data_file('telegram').open('rb'), filename='blah').filename == 'blah' assert ( - InputFile(open('tests/data/telegram', 'rb'), filename='blah.jpg').filename - == 'blah.jpg' + InputFile(data_file('telegram').open('rb'), filename='blah.jpg').filename == 'blah.jpg' ) class MockedFileobject: # A open(?, 'rb') without a .name def __init__(self, f): - self.f = open(f, 'rb') + self.f = f.open('rb') def read(self): return self.f.read() - assert InputFile(MockedFileobject('tests/data/telegram.jpg')).filename == 'image.jpeg' + assert InputFile(MockedFileobject(data_file('telegram.jpg'))).filename == 'image.jpeg' assert ( - InputFile(MockedFileobject('tests/data/telegram.jpg'), filename='blah').filename + InputFile(MockedFileobject(data_file('telegram.jpg')), filename='blah').filename == 'blah' ) assert ( - InputFile(MockedFileobject('tests/data/telegram.jpg'), filename='blah.jpg').filename + InputFile(MockedFileobject(data_file('telegram.jpg')), filename='blah.jpg').filename == 'blah.jpg' ) assert ( - InputFile(MockedFileobject('tests/data/telegram')).filename + InputFile(MockedFileobject(data_file('telegram'))).filename == 'application.octet-stream' ) assert ( - InputFile(MockedFileobject('tests/data/telegram'), filename='blah').filename == 'blah' + InputFile(MockedFileobject(data_file('telegram')), filename='blah').filename == 'blah' ) assert ( - InputFile(MockedFileobject('tests/data/telegram'), filename='blah.jpg').filename + InputFile(MockedFileobject(data_file('telegram')), filename='blah.jpg').filename == 'blah.jpg' ) def test_send_bytes(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 - with Path('tests/data/text_file.txt').open('rb') as file: - message = bot.send_document(chat_id, file.read()) - + message = bot.send_document(chat_id, data_file('text_file.txt').read_bytes()) out = BytesIO() + assert message.document.get_file().download(out=out) + out.seek(0) + assert out.read().decode('utf-8') == 'PTB Rocks!' diff --git a/tests/test_inputmedia.py b/tests/test_inputmedia.py index 378a6b260..0fc2b635f 100644 --- a/tests/test_inputmedia.py +++ b/tests/test_inputmedia.py @@ -16,8 +16,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. -from pathlib import Path - import pytest from flaky import flaky @@ -48,7 +46,7 @@ from .test_photo import _photo, photo_file, photo, thumb # noqa: F401 # noinspection PyUnresolvedReferences from .test_video import video, video_file # noqa: F401 -from tests.conftest import expect_bad_request +from tests.conftest import expect_bad_request, data_file @pytest.fixture(scope='class') @@ -178,10 +176,10 @@ class TestInputMediaVideo: def test_with_local_files(self): input_media_video = InputMediaVideo( - 'tests/data/telegram.mp4', thumb='tests/data/telegram.jpg' + data_file('telegram.mp4'), thumb=data_file('telegram.jpg') ) - assert input_media_video.media == (Path.cwd() / 'tests/data/telegram.mp4/').as_uri() - assert input_media_video.thumb == (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() + assert input_media_video.media == data_file('telegram.mp4').as_uri() + assert input_media_video.thumb == data_file('telegram.jpg').as_uri() class TestInputMediaPhoto: @@ -229,8 +227,8 @@ class TestInputMediaPhoto: assert input_media_photo.caption == "test 2" def test_with_local_files(self): - input_media_photo = InputMediaPhoto('tests/data/telegram.mp4') - assert input_media_photo.media == (Path.cwd() / 'tests/data/telegram.mp4/').as_uri() + input_media_photo = InputMediaPhoto(data_file('telegram.mp4')) + assert input_media_photo.media == data_file('telegram.mp4').as_uri() class TestInputMediaAnimation: @@ -286,10 +284,10 @@ class TestInputMediaAnimation: def test_with_local_files(self): input_media_animation = InputMediaAnimation( - 'tests/data/telegram.mp4', thumb='tests/data/telegram.jpg' + data_file('telegram.mp4'), thumb=data_file('telegram.jpg') ) - assert input_media_animation.media == (Path.cwd() / 'tests/data/telegram.mp4').as_uri() - assert input_media_animation.thumb == (Path.cwd() / 'tests/data/telegram.jpg').as_uri() + assert input_media_animation.media == data_file('telegram.mp4').as_uri() + assert input_media_animation.thumb == data_file('telegram.jpg').as_uri() class TestInputMediaAudio: @@ -351,10 +349,10 @@ class TestInputMediaAudio: def test_with_local_files(self): input_media_audio = InputMediaAudio( - 'tests/data/telegram.mp4', thumb='tests/data/telegram.jpg' + data_file('telegram.mp4'), thumb=data_file('telegram.jpg') ) - assert input_media_audio.media == (Path.cwd() / 'tests/data/telegram.mp4/').as_uri() - assert input_media_audio.thumb == (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() + assert input_media_audio.media == data_file('telegram.mp4').as_uri() + assert input_media_audio.thumb == data_file('telegram.jpg').as_uri() class TestInputMediaDocument: @@ -413,10 +411,10 @@ class TestInputMediaDocument: def test_with_local_files(self): input_media_document = InputMediaDocument( - 'tests/data/telegram.mp4', thumb='tests/data/telegram.jpg' + data_file('telegram.mp4'), thumb=data_file('telegram.jpg') ) - assert input_media_document.media == (Path.cwd() / 'tests/data/telegram.mp4').as_uri() - assert input_media_document.thumb == (Path.cwd() / 'tests/data/telegram.jpg').as_uri() + assert input_media_document.media == data_file('telegram.mp4').as_uri() + assert input_media_document.thumb == data_file('telegram.jpg').as_uri() @pytest.fixture(scope='function') # noqa: F811 @@ -507,15 +505,20 @@ class TestSendMediaGroup: @flaky(3, 1) # noqa: F811 def test_send_media_group_new_files( - self, bot, chat_id, video_file, photo_file, animation_file # noqa: F811 - ): # noqa: F811 + self, + bot, + chat_id, + video_file, # noqa: F811 + photo_file, # noqa: F811 + animation_file, # noqa: F811 + ): def func(): return bot.send_media_group( chat_id, [ InputMediaVideo(video_file), InputMediaPhoto(photo_file), - InputMediaPhoto(Path('tests/data/telegram.jpg').read_bytes()), + InputMediaPhoto(data_file('telegram.jpg').read_bytes()), ], ) diff --git a/tests/test_photo.py b/tests/test_photo.py index d1b7f3046..1b8308f55 100644 --- a/tests/test_photo.py +++ b/tests/test_photo.py @@ -30,12 +30,13 @@ from tests.conftest import ( check_shortcut_call, check_shortcut_signature, check_defaults_handling, + data_file, ) @pytest.fixture(scope='function') def photo_file(): - f = open('tests/data/telegram.jpg', 'rb') + f = data_file('telegram.jpg').open('rb') yield f f.close() @@ -43,7 +44,7 @@ def photo_file(): @pytest.fixture(scope='class') def _photo(bot, chat_id): def func(): - with Path('tests/data/telegram.jpg').open('rb') as f: + with data_file('telegram.jpg').open('rb') as f: return bot.send_photo(chat_id, photo=f, timeout=50).photo return expect_bad_request(func, 'Type of file mismatch', 'Telegram did not accept the file.') @@ -232,8 +233,8 @@ class TestPhoto: def test_send_photo_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag @@ -343,7 +344,7 @@ class TestPhoto: """ Regression test for https://github.com/python-telegram-bot/python-telegram-bot/issues/1202 """ - with Path('tests/data/测试.png').open('rb') as f: + with data_file('测试.png').open('rb') as f: message = bot.send_photo(photo=f, chat_id=chat_id) photo = message.photo[-1] @@ -356,7 +357,7 @@ class TestPhoto: @flaky(3, 1) def test_send_bytesio_jpg_file(self, bot, chat_id): - filepath: Path = Path('tests/data/telegram_no_standard_header.jpg') + filepath = data_file('telegram_no_standard_header.jpg') # raw image bytes raw_bytes = BytesIO(filepath.read_bytes()) diff --git a/tests/test_request.py b/tests/test_request.py index 70d4ec5b1..cc1c3ba2b 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -22,6 +22,7 @@ import pytest from telegram.error import TelegramError from telegram.request import Request +from tests.conftest import data_file def test_slot_behaviour(mro_slots): @@ -58,7 +59,7 @@ def test_parse_illegal_json(): ids=['str destination_path', 'pathlib.Path destination_path'], ) def test_download(destination_path_type): - destination_filepath = Path.cwd() / 'tests' / 'data' / 'downloaded_request.txt' + destination_filepath = data_file('downloaded_request.txt') request = Request() request.download("http://google.com", destination_path_type(destination_filepath)) assert destination_filepath.is_file() diff --git a/tests/test_sticker.py b/tests/test_sticker.py index 905278c83..f2e79a5d8 100644 --- a/tests/test_sticker.py +++ b/tests/test_sticker.py @@ -25,30 +25,35 @@ from flaky import flaky from telegram import Sticker, PhotoSize, StickerSet, Audio, MaskPosition, Bot from telegram.error import BadRequest, TelegramError -from tests.conftest import check_shortcut_call, check_shortcut_signature, check_defaults_handling +from tests.conftest import ( + check_shortcut_call, + check_shortcut_signature, + check_defaults_handling, + data_file, +) @pytest.fixture(scope='function') def sticker_file(): - with Path('tests/data/telegram.webp').open('rb') as file: + with data_file('telegram.webp').open('rb') as file: yield file @pytest.fixture(scope='class') def sticker(bot, chat_id): - with Path('tests/data/telegram.webp').open('rb') as f: + with data_file('telegram.webp').open('rb') as f: return bot.send_sticker(chat_id, sticker=f, timeout=50).sticker @pytest.fixture(scope='function') def animated_sticker_file(): - with Path('tests/data/telegram_animated_sticker.tgs').open('rb') as f: + with data_file('telegram_animated_sticker.tgs').open('rb') as f: yield f @pytest.fixture(scope='class') def animated_sticker(bot, chat_id): - with Path('tests/data/telegram_animated_sticker.tgs').open('rb') as f: + with data_file('telegram_animated_sticker.tgs').open('rb') as f: return bot.send_sticker(chat_id, sticker=f, timeout=50).sticker @@ -226,8 +231,8 @@ class TestSticker: def test_send_sticker_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag @@ -375,7 +380,7 @@ def video_sticker_set(bot): @pytest.fixture(scope='function') def sticker_set_thumb_file(): - with Path('tests/data/sticker_set_thumb.png').open('rb') as file: + with data_file('sticker_set_thumb.png').open('rb') as file: yield file @@ -452,7 +457,7 @@ class TestStickerSet: @flaky(3, 1) def test_bot_methods_1_png(self, bot, chat_id, sticker_file): - with Path('tests/data/telegram_sticker.png').open('rb') as f: + with data_file('telegram_sticker.png').open('rb') as f: # chat_id was hardcoded as 95205500 but it stopped working for some reason file = bot.upload_sticker_file(chat_id, f) assert file @@ -473,7 +478,7 @@ class TestStickerSet: assert bot.add_sticker_to_set( chat_id, f'animated_test_by_{bot.username}', - tgs_sticker=Path('tests/data/telegram_animated_sticker.tgs').open('rb'), + tgs_sticker=data_file('telegram_animated_sticker.tgs').open('rb'), emojis='😄', ) @@ -555,8 +560,8 @@ class TestStickerSet: 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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag @@ -570,8 +575,8 @@ class TestStickerSet: 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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag @@ -597,8 +602,8 @@ class TestStickerSet: def test_add_sticker_to_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag @@ -612,8 +617,8 @@ class TestStickerSet: def test_set_sticker_set_thumb_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag diff --git a/tests/test_updater.py b/tests/test_updater.py index 5a765afb2..6d1912899 100644 --- a/tests/test_updater.py +++ b/tests/test_updater.py @@ -23,6 +23,7 @@ import signal import sys import threading from contextlib import contextmanager +from pathlib import Path from flaky import flaky from functools import partial @@ -366,8 +367,8 @@ class TestUpdater: ip, port, url_path='TOKEN', - cert='./tests/test_updater.py', - key='./tests/test_updater.py', + cert=Path(__file__).as_posix(), + key=Path(__file__).as_posix(), bootstrap_retries=0, drop_pending_updates=False, webhook_url=None, @@ -420,7 +421,7 @@ class TestUpdater: ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port - updater.start_webhook(ip, port, webhook_url=None, cert='./tests/test_updater.py') + updater.start_webhook(ip, port, webhook_url=None, cert=Path(__file__).as_posix()) sleep(0.2) # Now, we send an update to the server via urlopen diff --git a/tests/test_video.py b/tests/test_video.py index 78820cf58..0f8ff3d1b 100644 --- a/tests/test_video.py +++ b/tests/test_video.py @@ -25,19 +25,24 @@ from flaky import flaky from telegram import Video, Voice, PhotoSize, MessageEntity, Bot from telegram.error import BadRequest, TelegramError from telegram.helpers import escape_markdown -from tests.conftest import check_shortcut_call, check_shortcut_signature, check_defaults_handling +from tests.conftest import ( + check_shortcut_call, + check_shortcut_signature, + check_defaults_handling, + data_file, +) @pytest.fixture(scope='function') def video_file(): - f = Path('tests/data/telegram.mp4').open('rb') + f = data_file('telegram.mp4').open('rb') yield f f.close() @pytest.fixture(scope='class') def video(bot, chat_id): - with Path('tests/data/telegram.mp4').open('rb') as f: + with data_file('telegram.mp4').open('rb') as f: return bot.send_video(chat_id, video=f, timeout=50).video @@ -230,8 +235,8 @@ class TestVideo: 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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag diff --git a/tests/test_videonote.py b/tests/test_videonote.py index ac38ce357..a5555693a 100644 --- a/tests/test_videonote.py +++ b/tests/test_videonote.py @@ -24,19 +24,24 @@ from flaky import flaky from telegram import VideoNote, Voice, PhotoSize, Bot from telegram.error import BadRequest, TelegramError -from tests.conftest import check_shortcut_call, check_shortcut_signature, check_defaults_handling +from tests.conftest import ( + check_shortcut_call, + check_shortcut_signature, + check_defaults_handling, + data_file, +) @pytest.fixture(scope='function') def video_note_file(): - f = open('tests/data/telegram2.mp4', 'rb') + f = data_file('telegram2.mp4').open('rb') yield f f.close() @pytest.fixture(scope='class') def video_note(bot, chat_id): - with Path('tests/data/telegram2.mp4').open('rb') as f: + with data_file('telegram2.mp4').open('rb') as f: return bot.send_video_note(chat_id, video_note=f, timeout=50).video_note @@ -168,8 +173,8 @@ class TestVideoNote: def test_send_video_note_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag diff --git a/tests/test_voice.py b/tests/test_voice.py index a905570ea..56fc57c32 100644 --- a/tests/test_voice.py +++ b/tests/test_voice.py @@ -17,7 +17,6 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import os -from pathlib import Path import pytest from flaky import flaky @@ -25,19 +24,24 @@ from flaky import flaky from telegram import Audio, Voice, MessageEntity, Bot from telegram.error import BadRequest, TelegramError from telegram.helpers import escape_markdown -from tests.conftest import check_shortcut_call, check_shortcut_signature, check_defaults_handling +from tests.conftest import ( + check_shortcut_call, + check_shortcut_signature, + check_defaults_handling, + data_file, +) @pytest.fixture(scope='function') def voice_file(): - f = Path('tests/data/telegram.ogg').open('rb') + f = data_file('telegram.ogg').open('rb') yield f f.close() @pytest.fixture(scope='class') def voice(bot, chat_id): - with Path('tests/data/telegram.ogg').open('rb') as f: + with data_file('telegram.ogg').open('rb') as f: return bot.send_voice(chat_id, voice=f, timeout=50).voice @@ -192,8 +196,8 @@ class TestVoice: def test_send_voice_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 - expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() - file = 'tests/data/telegram.jpg' + file = data_file('telegram.jpg') + expected = file.as_uri() def make_assertion(_, data, *args, **kwargs): nonlocal test_flag diff --git a/tests/test_warnings.py b/tests/test_warnings.py index 1d2bec3d4..40d0ca35e 100644 --- a/tests/test_warnings.py +++ b/tests/test_warnings.py @@ -16,13 +16,14 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. -import pathlib +from pathlib import Path from collections import defaultdict import pytest from telegram._utils.warnings import warn from telegram.warnings import PTBUserWarning, PTBRuntimeWarning, PTBDeprecationWarning +from tests.conftest import PROJECT_ROOT_PATH class TestWarnings: @@ -64,25 +65,23 @@ class TestWarnings: make_assertion(PTBUserWarning) def test_warn(self, recwarn): - expected_file = ( - pathlib.Path(__file__).parent.parent.resolve() / 'telegram' / '_utils' / 'warnings.py' - ) + expected_file = PROJECT_ROOT_PATH / 'telegram' / '_utils' / 'warnings.py' warn('test message') assert len(recwarn) == 1 assert recwarn[0].category is PTBUserWarning assert str(recwarn[0].message) == 'test message' - assert pathlib.Path(recwarn[0].filename) == expected_file, "incorrect stacklevel!" + assert Path(recwarn[0].filename) == expected_file, "incorrect stacklevel!" warn('test message 2', category=PTBRuntimeWarning) assert len(recwarn) == 2 assert recwarn[1].category is PTBRuntimeWarning assert str(recwarn[1].message) == 'test message 2' - assert pathlib.Path(recwarn[1].filename) == expected_file, "incorrect stacklevel!" + assert Path(recwarn[1].filename) == expected_file, "incorrect stacklevel!" warn('test message 3', stacklevel=1, category=PTBDeprecationWarning) - expected_file = pathlib.Path(__file__) + expected_file = Path(__file__) assert len(recwarn) == 3 assert recwarn[2].category is PTBDeprecationWarning assert str(recwarn[2].message) == 'test message 3' - assert pathlib.Path(recwarn[2].filename) == expected_file, "incorrect stacklevel!" + assert Path(recwarn[2].filename) == expected_file, "incorrect stacklevel!"