All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 25s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
381 lines
17 KiB
Python
381 lines
17 KiB
Python
"""Юниты чистых функций bot.py: источники, VK, извлечение URL, локали, тексты,
|
||
классификация ошибок и разбор ответа сервиса, заголовки, подпись."""
|
||
import html
|
||
import re
|
||
import string
|
||
from types import SimpleNamespace
|
||
from urllib.parse import quote
|
||
|
||
import pytest
|
||
|
||
import bot
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# detect_video_source
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('url, expected', [
|
||
('https://youtu.be/dQw4w9WgXcQ', 'youtube'),
|
||
('https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'youtube'),
|
||
('https://m.youtube.com/shorts/abc', 'youtube'),
|
||
('https://music.youtube.com/watch?v=abc', 'youtube'),
|
||
('https://www.youtube-nocookie.com/embed/abc', 'youtube'),
|
||
('HTTPS://WWW.YOUTUBE.COM/watch?v=abc', 'youtube'),
|
||
('https://www.youtube.com./watch?v=abc', 'youtube'), # FQDN с точкой
|
||
('https://youtube.com:443/watch?v=abc', 'youtube'),
|
||
('https://www.instagram.com/reel/Dak0fDTMv_i/', 'instagram'),
|
||
('https://instagram.com/p/abc/', 'instagram'),
|
||
('https://vk.com/video-77521_162222515', 'vk'),
|
||
('https://m.vk.com/video-1_2', 'vk'),
|
||
('https://vk.ru/video-1_2', 'vk'),
|
||
('https://vkontakte.ru/video-1_2', 'vk'),
|
||
('https://vkvideo.ru/video-1_2', 'vk'), # был xfail
|
||
('https://vm.tiktok.com/ZM123/', 'tiktok'),
|
||
('https://vt.tiktok.com/ZS123/', 'tiktok'),
|
||
('https://www.tiktok.com/@user/video/123', 'tiktok'),
|
||
('https://www.yapfiles.ru/show/3532099/30faa897f5a34bb58c018f909a6f1fae.mp4.html', 'yapfiles'),
|
||
# ложные срабатывания
|
||
('https://example.com/?u=https://youtube.com', 'unknown'),
|
||
('https://notyoutube.com.evil.io/x', 'unknown'), # был xfail
|
||
('https://youtube.com.evil.io/x', 'unknown'),
|
||
('https://notyoutube.com/x', 'unknown'),
|
||
('https://youtube.com@evil.io/x', 'unknown'), # userinfo-трюк
|
||
('https://evil.io/youtube.com/watch', 'unknown'),
|
||
('https://fakevk.com/video-1_2', 'unknown'),
|
||
('', 'unknown'),
|
||
('not a url', 'unknown'),
|
||
])
|
||
def test_detect_video_source(url, expected):
|
||
assert bot.detect_video_source(url) == expected
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# is_vk_video_url
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('url, expected', [
|
||
('https://vk.com/video-123_456', True),
|
||
('https://vk.com/video123_456', True),
|
||
('https://vk.com/clip-123_456', True),
|
||
('https://vk.com/video-123_456?list=ln-abc', True),
|
||
('https://vk.com/wall-1_2?z=video-1_2%2Fvideo', True),
|
||
('https://vk.com/feed?z=clip-1_2', True),
|
||
('https://vk.com/video?z=video-1_2%2Fpl_cat_trends', True),
|
||
('https://vkvideo.ru/video-1_2', True),
|
||
('https://vk.ru/clip-1_2', True),
|
||
('https://m.vk.com/video-1_2', True),
|
||
('https://vk.com/durov', False),
|
||
('https://vk.com/public123', False),
|
||
('https://vk.com/videos-123', False), # альбом — был xfail
|
||
('https://vk.com/video', False),
|
||
('https://vk.com/wall-1_2', False),
|
||
('https://vk.com/video-1_2abc', False),
|
||
('https://youtube.com/video1', False),
|
||
('https://evil.io/video-1_2', False),
|
||
])
|
||
def test_is_vk_video_url(url, expected):
|
||
assert bot.is_vk_video_url(url) is expected
|
||
|
||
|
||
def test_is_vk_video_url_embed():
|
||
assert bot.is_vk_video_url('https://vk.com/video_ext.php?oid=-1&id=2&hash=abc')
|
||
assert not bot.is_vk_video_url('https://vk.com/video_ext.php?hash=abc')
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# extract_urls_from_text / strip_urls
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('text, expected', [
|
||
('смотри https://youtu.be/abc и http://vk.com/video1_2',
|
||
['https://youtu.be/abc', 'http://vk.com/video1_2']),
|
||
('<https://youtu.be/abc>', ['https://youtu.be/abc']),
|
||
('ftp://x.ru/a www.youtube.com/watch?v=1', []),
|
||
('https://youtu.be/abc, потом', ['https://youtu.be/abc']), # был xfail
|
||
('(https://youtu.be/abc)', ['https://youtu.be/abc']), # был xfail
|
||
('вот: https://youtu.be/abc.', ['https://youtu.be/abc']),
|
||
('«https://youtu.be/abc»', ['https://youtu.be/abc']),
|
||
('"https://youtu.be/abc"!', ['https://youtu.be/abc']),
|
||
('https://youtu.be/abc?!', ['https://youtu.be/abc']),
|
||
('https://www.youtube.com/watch?v=abc&t=10s', ['https://www.youtube.com/watch?v=abc&t=10s']),
|
||
('https://vk.com/wall-1_2?z=video-1_2%2Fvideo', ['https://vk.com/wall-1_2?z=video-1_2%2Fvideo']),
|
||
('строка1\nhttps://youtu.be/a\nhttps://youtu.be/b', ['https://youtu.be/a', 'https://youtu.be/b']),
|
||
('без ссылок', []),
|
||
('', []),
|
||
])
|
||
def test_extract_urls_from_text(text, expected):
|
||
assert bot.extract_urls_from_text(text) == expected
|
||
|
||
|
||
def test_strip_urls():
|
||
assert bot.strip_urls('глянь https://youtu.be/abc это\n огонь') == 'глянь это огонь'
|
||
assert bot.strip_urls('https://youtu.be/abc') == ''
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Локали и тексты
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('code, expected', [
|
||
('ru', 'ru'), ('RU-ru', 'ru'), ('ru_RU', 'ru'), ('rus', 'ru'),
|
||
('uk', 'ru'), ('be', 'ru'), ('kk', 'ru'), ('be-ru', 'ru'), ('kk-KZ', 'ru'), ('uk-UA', 'ru'),
|
||
('en', 'en'), ('en-US', 'en'), ('de', 'en'), ('uz', 'en'), (None, 'en'), ('', 'en'),
|
||
])
|
||
def test_get_locale_from_language_code(code, expected):
|
||
assert bot.get_locale_from_language_code(code) == expected
|
||
|
||
|
||
def test_get_text_substitution():
|
||
ru = bot.get_text('ru', 'queue_position', position=3, ahead=2)
|
||
en = bot.get_text('en', 'queue_position', position=3, ahead=2)
|
||
assert '3' in ru and '2' in ru and '{' not in ru
|
||
assert '#3' in en and '2 video' in en and '{' not in en
|
||
|
||
|
||
def test_get_text_unknown_locale_falls_back_to_en():
|
||
assert bot.get_text('de', 'start') == bot.TEXTS['en']['start']
|
||
|
||
|
||
def test_get_text_unknown_key_returns_key():
|
||
assert bot.get_text('ru', 'no_such_key') == 'no_such_key'
|
||
|
||
|
||
def test_get_text_without_kwargs_is_raw():
|
||
assert '{position}' in bot.get_text('ru', 'queue_position')
|
||
|
||
|
||
def test_get_text_size_format():
|
||
assert re.search(r'51(\.5)? MB', bot.get_text('en', 'error_file_too_large', size_mb=51.456))
|
||
assert re.search(r'51(,|\.)?5? МБ', bot.get_text('ru', 'error_file_too_large', size_mb=51.456))
|
||
|
||
|
||
def test_texts_same_keys():
|
||
assert set(bot.TEXTS['ru']) == set(bot.TEXTS['en'])
|
||
|
||
|
||
def _placeholders(s):
|
||
return {f for _, f, _, _ in string.Formatter().parse(s) if f}
|
||
|
||
|
||
@pytest.mark.parametrize('key', sorted(bot.TEXTS['ru']))
|
||
def test_texts_same_placeholders(key):
|
||
assert _placeholders(bot.TEXTS['ru'][key]) == _placeholders(bot.TEXTS['en'][key])
|
||
|
||
|
||
_ALLOWED_TAGS = {'b', 'i', 'u', 's', 'a', 'code', 'pre', 'strong', 'em'}
|
||
|
||
|
||
@pytest.mark.parametrize('locale', ['ru', 'en'])
|
||
@pytest.mark.parametrize('key', sorted(bot.TEXTS['ru']))
|
||
def test_texts_are_valid_telegram_html(locale, key):
|
||
"""Тексты уходят с parse_mode=HTML: только разрешённые теги, '&' — только сущности."""
|
||
s = bot.TEXTS[locale][key]
|
||
tags = re.findall(r'<(/?)([a-zA-Z]+)[^>]*>', s)
|
||
assert {t for _, t in tags} <= _ALLOWED_TAGS
|
||
stripped = re.sub(r'<(/?)([a-zA-Z]+)[^>]*>', '', s)
|
||
assert '<' not in stripped and '>' not in stripped
|
||
assert not re.search(r'&(?!(amp|lt|gt|quot|#\d+);)', s)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Классификация ошибок бота
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('text, expected', [
|
||
("This content can't be seen by certain audiences", 'sensitive_content'),
|
||
('[download] File is larger than max-filesize (60000000 bytes > 52428800 bytes)', 'too_large'),
|
||
("Sign in to confirm you're not a bot. Use --cookies-from-browser", 'login_required'),
|
||
('Requested content is not available, rate-limit reached or login required', 'login_required'),
|
||
('Private video', 'private_or_removed'),
|
||
('Video unavailable', 'private_or_removed'),
|
||
('Видео недоступно', 'private_or_removed'),
|
||
('ERROR: Unsupported URL: https://vk.com/durov', 'unsupported_url'),
|
||
('Read timed out. (read timeout=30)', 'timeout'),
|
||
('Your IP address is blocked from accessing this post', 'download_failed'),
|
||
('', 'download_failed'),
|
||
(None, 'download_failed'),
|
||
])
|
||
def test_classify_error_text(text, expected):
|
||
assert bot.classify_error_text(text) == expected
|
||
|
||
|
||
def _resp(status, body, source='youtube'):
|
||
if isinstance(body, dict):
|
||
import json
|
||
body = json.dumps(body).encode()
|
||
return bot._error_from_response(source, status, body)
|
||
|
||
|
||
@pytest.mark.parametrize('status, body, expected', [
|
||
(422, {'error': 'Private video', 'code': 'private_or_removed'}, 'private_or_removed'),
|
||
(422, {'error': 'x', 'code': 'login_required'}, 'login_required'),
|
||
(422, {'error': 'x', 'code': 'sensitive_content'}, 'sensitive_content'),
|
||
(400, {'error': 'x', 'code': 'unsupported_url'}, 'unsupported_url'),
|
||
(400, {'error': 'x', 'code': 'bad_request'}, 'bad_request'),
|
||
(413, {'error': 'x', 'code': 'too_large'}, 'too_large'),
|
||
(504, {'error': 'x', 'code': 'timeout'}, 'timeout'),
|
||
# generic download_failed уточняется по тексту
|
||
(500, {'error': 'ERROR: Unsupported URL: https://vk.com/durov', 'code': 'download_failed'}, 'unsupported_url'),
|
||
(500, {'error': 'boom', 'code': 'download_failed'}, 'download_failed'),
|
||
# без поля code / не JSON
|
||
(413, b'<html>Request Entity Too Large</html>', 'too_large'),
|
||
(504, b'Gateway Timeout', 'timeout'),
|
||
(502, b'<html>Bad Gateway</html>', 'service_down'),
|
||
(503, b'Service Unavailable', 'service_down'),
|
||
(500, {'error': 'Sign in to confirm your age'}, 'login_required'),
|
||
(400, {'error': 'x', 'code': 'something_new'}, 'download_failed'),
|
||
])
|
||
def test_error_from_response(status, body, expected):
|
||
err = _resp(status, body)
|
||
assert err.code == expected
|
||
assert err.http_status == status
|
||
|
||
|
||
def test_error_from_response_too_large_size_from_ytdlp_text():
|
||
err = _resp(413, {'error': 'File is larger than max-filesize (60000000 bytes > 52428800 bytes)',
|
||
'code': 'too_large'})
|
||
assert err.size_mb == pytest.approx(60000000 / 1048576)
|
||
|
||
|
||
def test_error_from_response_too_large_size_from_factory_text():
|
||
"""Регрессия: фабрика сервисов пишет «Файл 57.2 МБ больше лимита 50 МБ» — бот ищет только
|
||
«N bytes», размер теряется и пользователь видит текст без размера."""
|
||
err = _resp(413, {'error': 'Файл 57.2 МБ больше лимита 50 МБ', 'code': 'too_large'})
|
||
assert err.size_mb == pytest.approx(57.2, abs=0.1)
|
||
|
||
|
||
@pytest.mark.parametrize('code', sorted(bot.ERROR_CODES))
|
||
@pytest.mark.parametrize('locale', ['ru', 'en'])
|
||
def test_user_error_text(code, locale):
|
||
text = bot.user_error_text(locale, 'youtube', bot.DownloadError(code, 'x', size_mb=60.0))
|
||
assert text and '{' not in text and '}' not in text
|
||
key = bot.ERROR_TEXT_KEYS.get(code, 'error')
|
||
assert key in bot.TEXTS[locale], f'ключ {key} для {code} отсутствует в TEXTS'
|
||
|
||
|
||
@pytest.mark.parametrize('locale', ['ru', 'en'])
|
||
def test_user_error_text_distinct_and_named(locale):
|
||
texts = {c: bot.user_error_text(locale, 'instagram', bot.DownloadError(c, 'x'))
|
||
for c in ('service_down', 'private_or_removed', 'login_required', 'sensitive_content',
|
||
'timeout', 'download_failed')}
|
||
assert len(set(texts.values())) == len(texts), 'у каждого класса свой текст'
|
||
assert 'Instagram' in texts['service_down'] and 'Instagram' in texts['login_required']
|
||
|
||
|
||
def test_user_error_text_too_large():
|
||
known = bot.user_error_text('ru', 'vk', bot.DownloadError('too_large', 'x', size_mb=73.4))
|
||
assert '73' in known
|
||
unknown = bot.user_error_text('ru', 'vk', bot.DownloadError('too_large', 'x'))
|
||
assert unknown == bot.get_text('ru', 'error_file_too_large_unknown')
|
||
|
||
|
||
def test_download_error_unknown_code_normalized():
|
||
assert bot.DownloadError('weird', 'x').code == 'download_failed'
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Заголовки ответа сервиса
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('title', [
|
||
'Me at the zoo', 'Тест видео №1 «ok»', '100% real', "Rock'n'roll & \"quotes\"",
|
||
'emoji 🎬 тут', 'a/b\\c?d', "utf-8''trap",
|
||
])
|
||
def test_title_roundtrip_with_factory_encoding(title):
|
||
"""Сервис кодирует X-Video-Title как quote(title, safe='') — бот обязан вернуть тот же title."""
|
||
assert bot._title_from_headers({'X-Video-Title': quote(title, safe='')}) == title
|
||
|
||
|
||
def test_title_falls_back_to_filename():
|
||
assert bot._title_from_headers({'Content-Disposition': 'attachment; filename="clip_1.mp4"'}) == 'clip_1'
|
||
assert bot._title_from_headers({}) is None
|
||
|
||
|
||
@pytest.mark.parametrize('header, expected', [
|
||
('attachment; filename="video.mp4"', 'video.mp4'),
|
||
("attachment; filename*=UTF-8''%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE.mp4", 'видео.mp4'),
|
||
('attachment; filename=plain.webm', 'plain.webm'),
|
||
('attachment; filename="a.mp4"; filename*=UTF-8\'\'b.mp4', 'b.mp4'),
|
||
('', None),
|
||
])
|
||
def test_parse_content_disposition(header, expected):
|
||
assert bot._parse_content_disposition(header) == expected
|
||
|
||
|
||
@pytest.mark.parametrize('ct, filename, expected', [
|
||
('video/mp4', None, 'mp4'),
|
||
('video/webm; charset=binary', None, 'webm'),
|
||
('application/octet-stream', 'x.mkv', 'mkv'),
|
||
('application/octet-stream', 'x.toolongext', 'mp4'),
|
||
('video/x-flv', None, 'xflv'),
|
||
('', None, 'mp4'),
|
||
])
|
||
def test_pick_extension(ct, filename, expected):
|
||
assert bot._pick_extension(ct, filename) == expected
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Подпись к видео
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def _item(chat_type='private', text='https://youtu.be/abc', first_name='Аня', url='https://youtu.be/abc',
|
||
locale='ru'):
|
||
user = SimpleNamespace(id=42, first_name=first_name, username='anya')
|
||
msg = SimpleNamespace(from_user=user, text=text)
|
||
return bot.QueueItem(original_message=msg, url=url, source='youtube', chat_id=-100 if chat_type != 'private' else 42,
|
||
chat_type=chat_type, user_id=42, locale=locale)
|
||
|
||
|
||
def _assert_valid_html(caption):
|
||
tags = re.findall(r'<(/?)([a-zA-Z]+)[^>]*>', caption)
|
||
opened = [t for slash, t in tags if not slash]
|
||
closed = [t for slash, t in tags if slash]
|
||
assert sorted(opened) == sorted(closed), caption
|
||
stripped = re.sub(r'<(/?)([a-zA-Z]+)[^>]*>', '', caption)
|
||
assert '<' not in stripped and '>' not in stripped
|
||
assert not re.search(r'&(?!(amp|lt|gt|quot|#x?[0-9a-fA-F]+);)', caption), caption
|
||
|
||
|
||
def test_caption_private_has_no_author():
|
||
cap = bot.build_caption(_item(), 'Title')
|
||
assert '👤' not in cap and 'Title' in cap
|
||
_assert_valid_html(cap)
|
||
|
||
|
||
def test_caption_group_has_author_and_text():
|
||
cap = bot.build_caption(_item('supergroup', text='смотри <b>это</b> https://youtu.be/abc'), 'T')
|
||
assert 'tg://user?id=42' in cap and 'Аня' in cap
|
||
assert '<b>это</b>' in cap
|
||
_assert_valid_html(cap)
|
||
|
||
|
||
def test_caption_escapes_title_and_name():
|
||
cap = bot.build_caption(_item('group', first_name='<i>x</i>'), '<script>&</script>')
|
||
assert '<script>' not in cap and '<script>&' in cap
|
||
_assert_valid_html(cap)
|
||
|
||
|
||
def test_caption_fallback_title():
|
||
assert bot.get_text('en', 'video_fallback') in bot.build_caption(_item(locale='en'), None)
|
||
|
||
|
||
def test_caption_long_title_does_not_split_entity():
|
||
"""Срез 200 символов после html.escape мог разрубить '&' (Telegram: can't parse entities)."""
|
||
cap = bot.build_caption(_item(), 'a' * 198 + '&&&&')
|
||
_assert_valid_html(cap)
|
||
|
||
|
||
def test_caption_long_url_keeps_link_tag():
|
||
"""caption[:1024] по сырому HTML обрезал бы тег <a href=...>."""
|
||
long_url = 'https://www.youtube.com/watch?v=abc&' + 'x=1&' * 250
|
||
cap = bot.build_caption(_item('group', text='т' * 300, url=long_url), 'T' * 200)
|
||
_assert_valid_html(cap)
|
||
|
||
|
||
def test_caption_shows_full_url_text():
|
||
"""Ссылка на видео видна в подписи целиком, а не спрятана под словом «Источник»."""
|
||
url = 'https://www.instagram.com/reel/Cvuh19eNWv_/?igsh=abc&utm_source=x'
|
||
for chat_type in ('private', 'supergroup'):
|
||
plain = bot.html_to_plain(bot.build_caption(_item(chat_type, url=url), 'T'))
|
||
assert url in plain, plain
|