Make Tests Agnostic of the CWD (#2727)

This commit is contained in:
eldbud 2021-10-13 09:12:48 +03:00 committed by Hinrich Mahler
parent 0cb8d50aea
commit 59014bee64
19 changed files with 216 additions and 164 deletions

View file

@ -23,6 +23,7 @@ import inspect
import os import os
import re import re
from collections import defaultdict from collections import defaultdict
from pathlib import Path
from queue import Queue from queue import Queue
from threading import Thread, Event from threading import Thread, Event
from time import sleep from time import sleep
@ -217,16 +218,24 @@ def updater(bot):
up.stop() 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') @pytest.fixture(scope='function')
def thumb_file(): def thumb_file():
f = open('tests/data/thumb.jpg', 'rb') f = data_file('thumb.jpg').open('rb')
yield f yield f
f.close() f.close()
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def class_thumb_file(): def class_thumb_file():
f = open('tests/data/thumb.jpg', 'rb') f = data_file('thumb.jpg').open('rb')
yield f yield f
f.close() f.close()

View file

@ -25,21 +25,27 @@ from flaky import flaky
from telegram import PhotoSize, Animation, Voice, MessageEntity, Bot from telegram import PhotoSize, Animation, Voice, MessageEntity, Bot
from telegram.error import BadRequest, TelegramError from telegram.error import BadRequest, TelegramError
from telegram.helpers import escape_markdown 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') @pytest.fixture(scope='function')
def animation_file(): def animation_file():
f = Path('tests/data/game.gif').open('rb') f = data_file('game.gif').open('rb')
yield f yield f
f.close() f.close()
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def animation(bot, chat_id): 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( 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 ).animation
@ -193,8 +199,8 @@ class TestAnimation:
def test_send_animation_local_files(self, monkeypatch, bot, chat_id): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag

View file

@ -25,22 +25,26 @@ from flaky import flaky
from telegram import Audio, Voice, MessageEntity, Bot from telegram import Audio, Voice, MessageEntity, Bot
from telegram.error import TelegramError from telegram.error import TelegramError
from telegram.helpers import escape_markdown 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') @pytest.fixture(scope='function')
def audio_file(): def audio_file():
f = Path('tests/data/telegram.mp3').open('rb') f = data_file('telegram.mp3').open('rb')
yield f yield f
f.close() f.close()
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def audio(bot, chat_id): def audio(bot, chat_id):
with Path('tests/data/telegram.mp3').open('rb') as f: with data_file('telegram.mp3').open('rb') as f:
return bot.send_audio( thumb = data_file('thumb.jpg')
chat_id, audio=f, timeout=50, thumb=Path('tests/data/thumb.jpg').open('rb') return bot.send_audio(chat_id, audio=f, timeout=50, thumb=thumb.open('rb')).audio
).audio
class TestAudio: class TestAudio:
@ -215,8 +219,8 @@ class TestAudio:
def test_send_audio_local_files(self, monkeypatch, bot, chat_id): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag

View file

@ -21,7 +21,6 @@ import logging
import time import time
import datetime as dtm import datetime as dtm
from collections import defaultdict from collections import defaultdict
from pathlib import Path
from platform import python_implementation from platform import python_implementation
import pytest import pytest
@ -59,9 +58,15 @@ from telegram.constants import MAX_INLINE_QUERY_RESULTS
from telegram.ext import ExtBot, InvalidCallbackData from telegram.ext import ExtBot, InvalidCallbackData
from telegram.error import BadRequest, InvalidToken, NetworkError, RetryAfter, TelegramError from telegram.error import BadRequest, InvalidToken, NetworkError, RetryAfter, TelegramError
from telegram._utils.datetime import from_timestamp, to_timestamp from telegram._utils.datetime import from_timestamp, to_timestamp
from telegram.helpers import escape_markdown
from telegram._utils.defaultvalue import DefaultValue 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 from tests.bots import FALLBACKS
@ -99,7 +104,7 @@ def message(bot, chat_id):
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def media_message(bot, chat_id): 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) 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. # get_file is tested multiple times in the test_*media* modules.
# Here we only test the behaviour for bot apis in local mode # Here we only test the behaviour for bot apis in local mode
def test_get_file_local_mode(self, bot, monkeypatch): 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): def _post(*args, **kwargs):
return { return {
@ -1924,14 +1929,14 @@ class TestBot:
def func(): def func():
assert bot.set_chat_photo(channel_id, f) 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.') 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): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag
@ -2008,7 +2013,7 @@ class TestBot:
# Test file uploading # Test file uploading
with pytest.raises(OkException): 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 # Test JSON submission
with pytest.raises(OkException): with pytest.raises(OkException):
@ -2032,7 +2037,7 @@ class TestBot:
# Test file uploading # Test file uploading
with pytest.raises(OkException): 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) @flaky(3, 1)
def test_send_message_entities(self, bot, chat_id): def test_send_message_entities(self, bot, chat_id):

View file

@ -29,12 +29,13 @@ from tests.conftest import (
check_shortcut_call, check_shortcut_call,
check_shortcut_signature, check_shortcut_signature,
check_defaults_handling, check_defaults_handling,
data_file,
) )
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def chatphoto_file(): def chatphoto_file():
f = open('tests/data/telegram.jpg', 'rb') f = data_file('telegram.jpg').open('rb')
yield f yield f
f.close() f.close()
@ -68,23 +69,24 @@ class TestChatPhoto:
@flaky(3, 1) @flaky(3, 1)
def test_get_and_download(self, bot, chat_photo): def test_get_and_download(self, bot, chat_photo):
jpg_file = Path('telegram.jpg')
new_file = bot.get_file(chat_photo.small_file_id) new_file = bot.get_file(chat_photo.small_file_id)
assert new_file.file_id == chat_photo.small_file_id assert new_file.file_id == chat_photo.small_file_id
assert new_file.file_path.startswith('https://') 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) new_file = bot.get_file(chat_photo.big_file_id)
assert new_file.file_id == chat_photo.big_file_id assert new_file.file_id == chat_photo.big_file_id
assert new_file.file_path.startswith('https://') 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_send_with_chat_photo(self, monkeypatch, bot, super_group_id, chat_photo):
def test(url, data, **kwargs): def test(url, data, **kwargs):

View file

@ -16,13 +16,12 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
from pathlib import Path
import pytest import pytest
from flaky import flaky from flaky import flaky
from telegram import constants from telegram import constants
from telegram.error import BadRequest from telegram.error import BadRequest
from tests.conftest import data_file
class TestConstants: class TestConstants:
@ -39,13 +38,11 @@ class TestConstants:
@flaky(3, 1) @flaky(3, 1)
def test_max_caption_length(self, bot, chat_id): def test_max_caption_length(self, bot, chat_id):
good_caption = 'a' * constants.MAX_CAPTION_LENGTH 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) good_msg = bot.send_photo(photo=f, caption=good_caption, chat_id=chat_id)
assert good_msg.caption == good_caption assert good_msg.caption == good_caption
bad_caption = good_caption + 'Z' bad_caption = good_caption + 'Z'
with pytest.raises( match = "Media_caption_too_long"
BadRequest, with pytest.raises(BadRequest, match=match), data_file('telegram.png').open('rb') as f:
match="Media_caption_too_long",
), open('tests/data/telegram.png', 'rb') as f:
bot.send_photo(photo=f, caption=bad_caption, chat_id=chat_id) bot.send_photo(photo=f, caption=bad_caption, chat_id=chat_id)

View file

@ -25,19 +25,24 @@ from flaky import flaky
from telegram import Document, PhotoSize, Voice, MessageEntity, Bot from telegram import Document, PhotoSize, Voice, MessageEntity, Bot
from telegram.error import BadRequest, TelegramError from telegram.error import BadRequest, TelegramError
from telegram.helpers import escape_markdown 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') @pytest.fixture(scope='function')
def document_file(): def document_file():
f = open('tests/data/telegram.png', 'rb') f = data_file('telegram.png').open('rb')
yield f yield f
f.close() f.close()
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def document(bot, chat_id): 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 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): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag

View file

@ -25,6 +25,7 @@ from flaky import flaky
from telegram import File, Voice from telegram import File, Voice
from telegram.error import TelegramError from telegram.error import TelegramError
from tests.conftest import data_file
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
@ -43,7 +44,7 @@ def local_file(bot):
return File( return File(
TestFile.file_id, TestFile.file_id,
TestFile.file_unique_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, file_size=TestFile.file_size,
bot=bot, bot=bot,
) )

View file

@ -16,25 +16,25 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
from pathlib import Path
import pytest import pytest
import telegram._utils.datetime import telegram._utils.datetime
import telegram._utils.files import telegram._utils.files
from telegram import InputFile, Animation, MessageEntity from telegram import InputFile, Animation, MessageEntity
from tests.conftest import TEST_DATA_PATH, data_file
class TestFiles: class TestFiles:
@pytest.mark.parametrize( @pytest.mark.parametrize(
'string,expected', 'string,expected',
[ [
('tests/data/game.gif', True), (str(data_file('game.gif')), True),
('tests/data', False), (str(TEST_DATA_PATH), False),
(str(Path.cwd() / 'tests' / 'data' / 'game.gif'), True), (str(data_file('game.gif')), True),
(str(Path.cwd() / 'tests' / 'data'), False), (str(TEST_DATA_PATH), False),
(Path.cwd() / 'tests' / 'data' / 'game.gif', True), (data_file('game.gif'), True),
(Path.cwd() / 'tests' / 'data', False), (TEST_DATA_PATH, False),
('https:/api.org/file/botTOKEN/document/file_3', False), ('https:/api.org/file/botTOKEN/document/file_3', False),
(None, False), (None, False),
], ],
@ -45,19 +45,13 @@ class TestFiles:
@pytest.mark.parametrize( @pytest.mark.parametrize(
'string,expected', 'string,expected',
[ [
('tests/data/game.gif', (Path.cwd() / 'tests' / 'data' / 'game.gif').as_uri()), (data_file('game.gif'), data_file('game.gif').as_uri()),
('tests/data', 'tests/data'), (TEST_DATA_PATH, TEST_DATA_PATH),
('file://foobar', 'file://foobar'), ('file://foobar', 'file://foobar'),
( (str(data_file('game.gif')), data_file('game.gif').as_uri()),
str(Path.cwd() / 'tests' / 'data' / 'game.gif'), (str(TEST_DATA_PATH), str(TEST_DATA_PATH)),
(Path.cwd() / 'tests' / 'data' / 'game.gif').as_uri(), (data_file('game.gif'), data_file('game.gif').as_uri()),
), (TEST_DATA_PATH, TEST_DATA_PATH),
(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'),
( (
'https:/api.org/file/botTOKEN/document/file_3', 'https:/api.org/file/botTOKEN/document/file_3',
'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 assert telegram._utils.files.parse_file_input(string) == expected
def test_parse_file_input_file_like(self): 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: with source_file.open('rb') as file:
parsed = telegram._utils.files.parse_file_input(file) parsed = telegram._utils.files.parse_file_input(file)
@ -86,7 +80,7 @@ class TestFiles:
assert parsed.filename == 'test_file' assert parsed.filename == 'test_file'
def test_parse_file_input_bytes(self): 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()) parsed = telegram._utils.files.parse_file_input(source_file.read_bytes())
assert isinstance(parsed, InputFile) assert isinstance(parsed, InputFile)

View file

@ -20,27 +20,32 @@ import logging
import subprocess import subprocess
import sys import sys
from io import BytesIO from io import BytesIO
from pathlib import Path
import pytest
from telegram import InputFile from telegram import InputFile
from tests.conftest import data_file
@pytest.fixture(scope='class')
def png_file():
return data_file('game.png')
class TestInputFile: class TestInputFile:
png = Path('tests/data/game.png')
def test_slot_behaviour(self, mro_slots): def test_slot_behaviour(self, mro_slots):
inst = InputFile(BytesIO(b'blah'), filename='tg.jpg') inst = InputFile(BytesIO(b'blah'), filename='tg.jpg')
for attr in inst.__slots__: for attr in inst.__slots__:
assert getattr(inst, attr, 'err') != 'err', f"got extra slot '{attr}'" assert getattr(inst, attr, 'err') != 'err', f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
def test_subprocess_pipe(self): def test_subprocess_pipe(self, png_file):
cmd_str = 'type' if sys.platform == 'win32' else 'cat' 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')) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=(sys.platform == 'win32'))
in_file = InputFile(proc.stdout) 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.mimetype == 'image/png'
assert in_file.filename == 'image.png' assert in_file.filename == 'image.png'
@ -53,9 +58,9 @@ class TestInputFile:
def test_mimetypes(self, caplog): def test_mimetypes(self, caplog):
# Only test a few to make sure logic works okay # Only test a few to make sure logic works okay
assert InputFile(open('tests/data/telegram.jpg', 'rb')).mimetype == 'image/jpeg' assert InputFile(data_file('telegram.jpg').open('rb')).mimetype == 'image/jpeg'
assert InputFile(open('tests/data/telegram.webp', 'rb')).mimetype == 'image/webp' assert InputFile(data_file('telegram.webp').open('rb')).mimetype == 'image/webp'
assert InputFile(open('tests/data/telegram.mp3', 'rb')).mimetype == 'audio/mpeg' assert InputFile(data_file('telegram.mp3').open('rb')).mimetype == 'audio/mpeg'
# Test guess from file # Test guess from file
assert InputFile(BytesIO(b'blah'), filename='tg.jpg').mimetype == 'image/jpeg' assert InputFile(BytesIO(b'blah'), filename='tg.jpg').mimetype == 'image/jpeg'
@ -70,61 +75,61 @@ class TestInputFile:
# Test string file # Test string file
with caplog.at_level(logging.DEBUG): 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 len(caplog.records) == 1
assert caplog.records[0].getMessage().startswith('Could not parse file content') assert caplog.records[0].getMessage().startswith('Could not parse file content')
def test_filenames(self): def test_filenames(self):
assert InputFile(open('tests/data/telegram.jpg', 'rb')).filename == 'telegram.jpg' assert InputFile(data_file('telegram.jpg').open('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='blah').filename == 'blah'
assert ( 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' == 'blah.jpg'
) )
assert InputFile(open('tests/data/telegram', 'rb')).filename == 'telegram' assert InputFile(data_file('telegram').open('rb')).filename == 'telegram'
assert InputFile(open('tests/data/telegram', 'rb'), filename='blah').filename == 'blah' assert InputFile(data_file('telegram').open('rb'), filename='blah').filename == 'blah'
assert ( assert (
InputFile(open('tests/data/telegram', 'rb'), filename='blah.jpg').filename InputFile(data_file('telegram').open('rb'), filename='blah.jpg').filename == 'blah.jpg'
== 'blah.jpg'
) )
class MockedFileobject: class MockedFileobject:
# A open(?, 'rb') without a .name # A open(?, 'rb') without a .name
def __init__(self, f): def __init__(self, f):
self.f = open(f, 'rb') self.f = f.open('rb')
def read(self): def read(self):
return self.f.read() 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 ( assert (
InputFile(MockedFileobject('tests/data/telegram.jpg'), filename='blah').filename InputFile(MockedFileobject(data_file('telegram.jpg')), filename='blah').filename
== 'blah' == 'blah'
) )
assert ( assert (
InputFile(MockedFileobject('tests/data/telegram.jpg'), filename='blah.jpg').filename InputFile(MockedFileobject(data_file('telegram.jpg')), filename='blah.jpg').filename
== 'blah.jpg' == 'blah.jpg'
) )
assert ( assert (
InputFile(MockedFileobject('tests/data/telegram')).filename InputFile(MockedFileobject(data_file('telegram'))).filename
== 'application.octet-stream' == 'application.octet-stream'
) )
assert ( assert (
InputFile(MockedFileobject('tests/data/telegram'), filename='blah').filename == 'blah' InputFile(MockedFileobject(data_file('telegram')), filename='blah').filename == 'blah'
) )
assert ( assert (
InputFile(MockedFileobject('tests/data/telegram'), filename='blah.jpg').filename InputFile(MockedFileobject(data_file('telegram')), filename='blah.jpg').filename
== 'blah.jpg' == 'blah.jpg'
) )
def test_send_bytes(self, bot, chat_id): def test_send_bytes(self, bot, chat_id):
# We test this here and not at the respective test modules because it's not worth # We test this here and not at the respective test modules because it's not worth
# duplicating the test for the different methods # duplicating the test for the different methods
with Path('tests/data/text_file.txt').open('rb') as file: message = bot.send_document(chat_id, data_file('text_file.txt').read_bytes())
message = bot.send_document(chat_id, file.read())
out = BytesIO() out = BytesIO()
assert message.document.get_file().download(out=out) assert message.document.get_file().download(out=out)
out.seek(0) out.seek(0)
assert out.read().decode('utf-8') == 'PTB Rocks!' assert out.read().decode('utf-8') == 'PTB Rocks!'

View file

@ -16,8 +16,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
from pathlib import Path
import pytest import pytest
from flaky import flaky from flaky import flaky
@ -48,7 +46,7 @@ from .test_photo import _photo, photo_file, photo, thumb # noqa: F401
# noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences
from .test_video import video, video_file # noqa: F401 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') @pytest.fixture(scope='class')
@ -178,10 +176,10 @@ class TestInputMediaVideo:
def test_with_local_files(self): def test_with_local_files(self):
input_media_video = InputMediaVideo( 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.media == data_file('telegram.mp4').as_uri()
assert input_media_video.thumb == (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() assert input_media_video.thumb == data_file('telegram.jpg').as_uri()
class TestInputMediaPhoto: class TestInputMediaPhoto:
@ -229,8 +227,8 @@ class TestInputMediaPhoto:
assert input_media_photo.caption == "test 2" assert input_media_photo.caption == "test 2"
def test_with_local_files(self): def test_with_local_files(self):
input_media_photo = InputMediaPhoto('tests/data/telegram.mp4') input_media_photo = InputMediaPhoto(data_file('telegram.mp4'))
assert input_media_photo.media == (Path.cwd() / 'tests/data/telegram.mp4/').as_uri() assert input_media_photo.media == data_file('telegram.mp4').as_uri()
class TestInputMediaAnimation: class TestInputMediaAnimation:
@ -286,10 +284,10 @@ class TestInputMediaAnimation:
def test_with_local_files(self): def test_with_local_files(self):
input_media_animation = InputMediaAnimation( 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.media == data_file('telegram.mp4').as_uri()
assert input_media_animation.thumb == (Path.cwd() / 'tests/data/telegram.jpg').as_uri() assert input_media_animation.thumb == data_file('telegram.jpg').as_uri()
class TestInputMediaAudio: class TestInputMediaAudio:
@ -351,10 +349,10 @@ class TestInputMediaAudio:
def test_with_local_files(self): def test_with_local_files(self):
input_media_audio = InputMediaAudio( 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.media == data_file('telegram.mp4').as_uri()
assert input_media_audio.thumb == (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() assert input_media_audio.thumb == data_file('telegram.jpg').as_uri()
class TestInputMediaDocument: class TestInputMediaDocument:
@ -413,10 +411,10 @@ class TestInputMediaDocument:
def test_with_local_files(self): def test_with_local_files(self):
input_media_document = InputMediaDocument( 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.media == data_file('telegram.mp4').as_uri()
assert input_media_document.thumb == (Path.cwd() / 'tests/data/telegram.jpg').as_uri() assert input_media_document.thumb == data_file('telegram.jpg').as_uri()
@pytest.fixture(scope='function') # noqa: F811 @pytest.fixture(scope='function') # noqa: F811
@ -507,15 +505,20 @@ class TestSendMediaGroup:
@flaky(3, 1) # noqa: F811 @flaky(3, 1) # noqa: F811
def test_send_media_group_new_files( def test_send_media_group_new_files(
self, bot, chat_id, video_file, photo_file, animation_file # noqa: F811 self,
): # noqa: F811 bot,
chat_id,
video_file, # noqa: F811
photo_file, # noqa: F811
animation_file, # noqa: F811
):
def func(): def func():
return bot.send_media_group( return bot.send_media_group(
chat_id, chat_id,
[ [
InputMediaVideo(video_file), InputMediaVideo(video_file),
InputMediaPhoto(photo_file), InputMediaPhoto(photo_file),
InputMediaPhoto(Path('tests/data/telegram.jpg').read_bytes()), InputMediaPhoto(data_file('telegram.jpg').read_bytes()),
], ],
) )

View file

@ -30,12 +30,13 @@ from tests.conftest import (
check_shortcut_call, check_shortcut_call,
check_shortcut_signature, check_shortcut_signature,
check_defaults_handling, check_defaults_handling,
data_file,
) )
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def photo_file(): def photo_file():
f = open('tests/data/telegram.jpg', 'rb') f = data_file('telegram.jpg').open('rb')
yield f yield f
f.close() f.close()
@ -43,7 +44,7 @@ def photo_file():
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def _photo(bot, chat_id): def _photo(bot, chat_id):
def func(): 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 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.') 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): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag
@ -343,7 +344,7 @@ class TestPhoto:
""" """
Regression test for https://github.com/python-telegram-bot/python-telegram-bot/issues/1202 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) message = bot.send_photo(photo=f, chat_id=chat_id)
photo = message.photo[-1] photo = message.photo[-1]
@ -356,7 +357,7 @@ class TestPhoto:
@flaky(3, 1) @flaky(3, 1)
def test_send_bytesio_jpg_file(self, bot, chat_id): 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 image bytes
raw_bytes = BytesIO(filepath.read_bytes()) raw_bytes = BytesIO(filepath.read_bytes())

View file

@ -22,6 +22,7 @@ import pytest
from telegram.error import TelegramError from telegram.error import TelegramError
from telegram.request import Request from telegram.request import Request
from tests.conftest import data_file
def test_slot_behaviour(mro_slots): def test_slot_behaviour(mro_slots):
@ -58,7 +59,7 @@ def test_parse_illegal_json():
ids=['str destination_path', 'pathlib.Path destination_path'], ids=['str destination_path', 'pathlib.Path destination_path'],
) )
def test_download(destination_path_type): 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 = Request()
request.download("http://google.com", destination_path_type(destination_filepath)) request.download("http://google.com", destination_path_type(destination_filepath))
assert destination_filepath.is_file() assert destination_filepath.is_file()

View file

@ -25,30 +25,35 @@ from flaky import flaky
from telegram import Sticker, PhotoSize, StickerSet, Audio, MaskPosition, Bot from telegram import Sticker, PhotoSize, StickerSet, Audio, MaskPosition, Bot
from telegram.error import BadRequest, TelegramError 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') @pytest.fixture(scope='function')
def sticker_file(): def sticker_file():
with Path('tests/data/telegram.webp').open('rb') as file: with data_file('telegram.webp').open('rb') as file:
yield file yield file
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def sticker(bot, chat_id): 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 return bot.send_sticker(chat_id, sticker=f, timeout=50).sticker
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def animated_sticker_file(): 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 yield f
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def animated_sticker(bot, chat_id): 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 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): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag
@ -375,7 +380,7 @@ def video_sticker_set(bot):
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def sticker_set_thumb_file(): 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 yield file
@ -452,7 +457,7 @@ class TestStickerSet:
@flaky(3, 1) @flaky(3, 1)
def test_bot_methods_1_png(self, bot, chat_id, sticker_file): 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 # chat_id was hardcoded as 95205500 but it stopped working for some reason
file = bot.upload_sticker_file(chat_id, f) file = bot.upload_sticker_file(chat_id, f)
assert file assert file
@ -473,7 +478,7 @@ class TestStickerSet:
assert bot.add_sticker_to_set( assert bot.add_sticker_to_set(
chat_id, chat_id,
f'animated_test_by_{bot.username}', 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='😄', emojis='😄',
) )
@ -555,8 +560,8 @@ class TestStickerSet:
def test_upload_sticker_file_local_files(self, monkeypatch, bot, chat_id): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag
@ -570,8 +575,8 @@ class TestStickerSet:
def test_create_new_sticker_set_local_files(self, monkeypatch, bot, chat_id): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag
@ -597,8 +602,8 @@ class TestStickerSet:
def test_add_sticker_to_set_local_files(self, monkeypatch, bot, chat_id): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag
@ -612,8 +617,8 @@ class TestStickerSet:
def test_set_sticker_set_thumb_local_files(self, monkeypatch, bot, chat_id): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag

View file

@ -23,6 +23,7 @@ import signal
import sys import sys
import threading import threading
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path
from flaky import flaky from flaky import flaky
from functools import partial from functools import partial
@ -366,8 +367,8 @@ class TestUpdater:
ip, ip,
port, port,
url_path='TOKEN', url_path='TOKEN',
cert='./tests/test_updater.py', cert=Path(__file__).as_posix(),
key='./tests/test_updater.py', key=Path(__file__).as_posix(),
bootstrap_retries=0, bootstrap_retries=0,
drop_pending_updates=False, drop_pending_updates=False,
webhook_url=None, webhook_url=None,
@ -420,7 +421,7 @@ class TestUpdater:
ip = '127.0.0.1' ip = '127.0.0.1'
port = randrange(1024, 49152) # Select random port 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) sleep(0.2)
# Now, we send an update to the server via urlopen # Now, we send an update to the server via urlopen

View file

@ -25,19 +25,24 @@ from flaky import flaky
from telegram import Video, Voice, PhotoSize, MessageEntity, Bot from telegram import Video, Voice, PhotoSize, MessageEntity, Bot
from telegram.error import BadRequest, TelegramError from telegram.error import BadRequest, TelegramError
from telegram.helpers import escape_markdown 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') @pytest.fixture(scope='function')
def video_file(): def video_file():
f = Path('tests/data/telegram.mp4').open('rb') f = data_file('telegram.mp4').open('rb')
yield f yield f
f.close() f.close()
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def video(bot, chat_id): 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 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): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag

View file

@ -24,19 +24,24 @@ from flaky import flaky
from telegram import VideoNote, Voice, PhotoSize, Bot from telegram import VideoNote, Voice, PhotoSize, Bot
from telegram.error import BadRequest, TelegramError 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') @pytest.fixture(scope='function')
def video_note_file(): def video_note_file():
f = open('tests/data/telegram2.mp4', 'rb') f = data_file('telegram2.mp4').open('rb')
yield f yield f
f.close() f.close()
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def video_note(bot, chat_id): 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 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): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag

View file

@ -17,7 +17,6 @@
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
import os import os
from pathlib import Path
import pytest import pytest
from flaky import flaky from flaky import flaky
@ -25,19 +24,24 @@ from flaky import flaky
from telegram import Audio, Voice, MessageEntity, Bot from telegram import Audio, Voice, MessageEntity, Bot
from telegram.error import BadRequest, TelegramError from telegram.error import BadRequest, TelegramError
from telegram.helpers import escape_markdown 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') @pytest.fixture(scope='function')
def voice_file(): def voice_file():
f = Path('tests/data/telegram.ogg').open('rb') f = data_file('telegram.ogg').open('rb')
yield f yield f
f.close() f.close()
@pytest.fixture(scope='class') @pytest.fixture(scope='class')
def voice(bot, chat_id): 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 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): 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 # For just test that the correct paths are passed as we have no local bot API set up
test_flag = False test_flag = False
expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri() file = data_file('telegram.jpg')
file = 'tests/data/telegram.jpg' expected = file.as_uri()
def make_assertion(_, data, *args, **kwargs): def make_assertion(_, data, *args, **kwargs):
nonlocal test_flag nonlocal test_flag

View file

@ -16,13 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
import pathlib from pathlib import Path
from collections import defaultdict from collections import defaultdict
import pytest import pytest
from telegram._utils.warnings import warn from telegram._utils.warnings import warn
from telegram.warnings import PTBUserWarning, PTBRuntimeWarning, PTBDeprecationWarning from telegram.warnings import PTBUserWarning, PTBRuntimeWarning, PTBDeprecationWarning
from tests.conftest import PROJECT_ROOT_PATH
class TestWarnings: class TestWarnings:
@ -64,25 +65,23 @@ class TestWarnings:
make_assertion(PTBUserWarning) make_assertion(PTBUserWarning)
def test_warn(self, recwarn): def test_warn(self, recwarn):
expected_file = ( expected_file = PROJECT_ROOT_PATH / 'telegram' / '_utils' / 'warnings.py'
pathlib.Path(__file__).parent.parent.resolve() / 'telegram' / '_utils' / 'warnings.py'
)
warn('test message') warn('test message')
assert len(recwarn) == 1 assert len(recwarn) == 1
assert recwarn[0].category is PTBUserWarning assert recwarn[0].category is PTBUserWarning
assert str(recwarn[0].message) == 'test message' 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) warn('test message 2', category=PTBRuntimeWarning)
assert len(recwarn) == 2 assert len(recwarn) == 2
assert recwarn[1].category is PTBRuntimeWarning assert recwarn[1].category is PTBRuntimeWarning
assert str(recwarn[1].message) == 'test message 2' 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) warn('test message 3', stacklevel=1, category=PTBDeprecationWarning)
expected_file = pathlib.Path(__file__) expected_file = Path(__file__)
assert len(recwarn) == 3 assert len(recwarn) == 3
assert recwarn[2].category is PTBDeprecationWarning assert recwarn[2].category is PTBDeprecationWarning
assert str(recwarn[2].message) == 'test message 3' 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!"