"""Поведение bot.py без Telegram: запрос к сервису (httpx.MockTransport), разбор входящих сообщений, очередь и воркер, cookie health-check. Async — через asyncio.run.""" import asyncio import json from types import SimpleNamespace from urllib.parse import quote import httpx import pytest import bot import db _RealAsyncClient = httpx.AsyncClient @pytest.fixture def env(tmp_path, monkeypatch, tmpdb): """Изолированное окружение бота: tmp video/, tmp SQLite, без пауз и без админ-бота.""" video = tmp_path / 'video' video.mkdir() monkeypatch.setattr(bot, 'DOWNLOADS_DIR', video) monkeypatch.setattr(bot, 'SERVICE_RETRY_PAUSE', 0) monkeypatch.setattr(bot, 'COOKIE_STATUS_FILE', tmp_path / 'cookie_state.json') monkeypatch.setattr(bot, 'queue_items', []) monkeypatch.setattr(bot, 'ADMIN_BOT', None) monkeypatch.setattr(bot, '_admin_alert_state', {}) db.init_database() return SimpleNamespace(video=video, tmp=tmp_path) def mock_http(monkeypatch, handler): """Все httpx.AsyncClient внутри bot ходят в handler(request) -> httpx.Response.""" calls = [] def wrapped(request): calls.append(request) return handler(request) def factory(*a, **kw): return _RealAsyncClient(*a, transport=httpx.MockTransport(wrapped), **kw) monkeypatch.setattr(bot.httpx, 'AsyncClient', factory) return calls # --------------------------------------------------------------------------- # fetch_from_service # --------------------------------------------------------------------------- def _ok_response(title='Тест «видео» & 100%', body=b'VIDEO' * 1000): return httpx.Response(200, content=body, headers={ 'Content-Type': 'video/mp4', 'Content-Disposition': 'attachment; filename="video_abc.mp4"', 'X-Video-Title': quote(title, safe='')}) def test_fetch_success(env, monkeypatch): calls = mock_http(monkeypatch, lambda r: _ok_response()) path, title = asyncio.run(bot.fetch_from_service('vk', 'https://vk.com/video-1_2', 42)) assert title == 'Тест «видео» & 100%' assert path.endswith('.mp4') and open(path, 'rb').read() == b'VIDEO' * 1000 assert len(calls) == 1 and json.loads(calls[0].content) == {'url': 'https://vk.com/video-1_2'} assert str(calls[0].url).endswith('/download/stream') @pytest.mark.parametrize('status, body, code, attempts', [ (422, {'error': 'Private video', 'code': 'private_or_removed'}, 'private_or_removed', 1), (422, {'error': 'x', 'code': 'login_required'}, 'login_required', 1), (413, {'error': 'x', 'code': 'too_large'}, 'too_large', 1), (400, {'error': 'x', 'code': 'unsupported_url'}, 'unsupported_url', 1), (504, {'error': 'x', 'code': 'timeout'}, 'timeout', 1), # download_failed не ретраится: сервис уже потратил свой бюджет попыток (~300 с) (500, {'error': 'boom', 'code': 'download_failed'}, 'download_failed', 1), (502, b'Bad Gateway', 'service_down', bot.SERVICE_RETRIES), ]) def test_fetch_error_codes_and_retries(env, monkeypatch, status, body, code, attempts): content = json.dumps(body).encode() if isinstance(body, dict) else body calls = mock_http(monkeypatch, lambda r: httpx.Response(status, content=content)) with pytest.raises(bot.DownloadError) as e: asyncio.run(bot.fetch_from_service('youtube', 'https://youtu.be/x', 1)) assert e.value.code == code assert len(calls) == attempts assert list(env.video.iterdir()) == [] def test_fetch_connect_error_is_service_down(env, monkeypatch): def handler(r): raise httpx.ConnectError('Connection refused') calls = mock_http(monkeypatch, handler) with pytest.raises(bot.DownloadError) as e: asyncio.run(bot.fetch_from_service('tiktok', 'https://www.tiktok.com/@a/video/1', 1)) assert e.value.code == 'service_down' and len(calls) == bot.SERVICE_RETRIES def test_fetch_read_timeout_not_retried(env, monkeypatch): """a9d1ffc: зависший сервис не должен держать очередь дольше одного read-таймаута.""" def handler(r): raise httpx.ReadTimeout('timed out') calls = mock_http(monkeypatch, handler) with pytest.raises(bot.DownloadError) as e: asyncio.run(bot.fetch_from_service('vk', 'https://vk.com/video-1_2', 1)) assert e.value.code == 'timeout' and len(calls) == 1 def test_http_timeout_covers_service_budget(): """read-таймаут бота должен быть больше бюджета YouTube-сервиса, иначе бот бросит готовый ответ.""" from conftest import load_service yt = load_service('youtube') budget = getattr(yt, 'TOTAL_BUDGET', yt.DOWNLOAD_TIMEOUT * 2) assert bot.HTTP_TIMEOUT.read > budget class _BrokenStream(httpx.AsyncByteStream): async def __aiter__(self): yield b'partial-data' raise httpx.ReadError('connection reset') def test_fetch_partial_file_removed(env, monkeypatch): state = {'n': 0} def handler(r): state['n'] += 1 if state['n'] == 1: return httpx.Response(200, headers={'Content-Type': 'video/mp4'}, stream=_BrokenStream()) return _ok_response(body=b'OK' * 10) mock_http(monkeypatch, handler) path, _ = asyncio.run(bot.fetch_from_service('youtube', 'https://youtu.be/x', 7)) assert [p.name for p in env.video.iterdir()] == [path.rsplit('/', 1)[-1]] # --------------------------------------------------------------------------- # handle_message # --------------------------------------------------------------------------- class FakeMessage: _ids = iter(range(1000, 10**6)) def __init__(self, text='', chat_type='private', chat_id=42, user_id=42, lang='ru', first_name='Аня', username='anya', thread_id=None): self.text = text self.message_thread_id = thread_id self.is_topic_message = thread_id is not None self.chat_id = chat_id self.chat = SimpleNamespace(type=chat_type) self.from_user = SimpleNamespace(id=user_id, username=username, first_name=first_name, language_code=lang) self.message_id = next(self._ids) self.replies, self.videos, self.edits, self.status_msgs = [], [], [], [] self.deleted = False async def reply_text(self, text, **kw): self.replies.append(text) status = FakeMessage(chat_type=self.chat.type, chat_id=self.chat_id) status.text = text self.status_msgs.append(status) return status async def edit_text(self, text, **kw): self.edits.append(text) self.text = text async def reply_video(self, **kw): kw['video'] = kw['video'].read() self.videos.append(kw) async def delete(self): self.deleted = True def _send(msg): return bot.handle_message(SimpleNamespace(message=msg), SimpleNamespace(job_queue=None, bot=None)) def _run_handlers(*msgs): async def go(): bot.download_queue = asyncio.Queue() bot.queue_lock = asyncio.Lock() for m in msgs: await _send(m) asyncio.run(go()) @pytest.mark.parametrize('text, chat_type, reply_key', [ ('привет', 'private', 'send_link'), ('https://example.com/video', 'private', 'unsupported_source'), ('https://vk.com/durov', 'private', 'error_vk_not_video'), ('привет', 'group', None), ('https://example.com/video', 'supergroup', None), ('https://vk.com/durov', 'group', None), ]) def test_handle_message_rejects(env, text, chat_type, reply_key): msg = FakeMessage(text, chat_type=chat_type, chat_id=42 if chat_type == 'private' else -100) _run_handlers(msg) expected = [bot.get_text('ru', reply_key)] if reply_key else [] assert msg.replies == expected assert bot.queue_items == [] def test_handle_message_enqueues_first_link(env): msg = FakeMessage('глянь https://youtu.be/a и https://youtu.be/b', lang='en') _run_handlers(msg) assert msg.replies[0] == bot.get_text('en', 'multiple_links', n=2) assert msg.replies[1] == bot.get_text('en', 'downloading') assert len(bot.queue_items) == 1 item = bot.queue_items[0] assert (item.url, item.source, item.locale, item.user_id) == ('https://youtu.be/a', 'youtube', 'en', 42) assert db.get_top_active_users() == [(42, 'anya', 'Аня', 1)] assert db.get_user_locale(42) == 'en' def test_handle_message_group_silent_about_multiple_links(env): msg = FakeMessage('https://youtu.be/a https://youtu.be/b', chat_type='group', chat_id=-100) _run_handlers(msg) assert msg.replies == [bot.get_text('ru', 'downloading')] def test_queue_positions_and_per_user_limit(env): msgs = [FakeMessage(f'https://youtu.be/{i}', chat_type='group', chat_id=-100, user_id=1) for i in range(4)] other = FakeMessage('https://youtu.be/z', chat_type='group', chat_id=-100, user_id=2) _run_handlers(*msgs, other) assert msgs[0].replies == [bot.get_text('ru', 'downloading')] assert msgs[1].replies == [bot.get_text('ru', 'queue_position', position=2, ahead=1)] assert msgs[3].replies == [bot.get_text('ru', 'queue_limit', limit=bot.QUEUE_LIMIT_PER_USER)] assert other.replies == [bot.get_text('ru', 'queue_position', position=4, ahead=3)] assert len(bot.queue_items) == 4 # счётчик ссылок — по user_id, а не по chat_id группы top = dict((u, c) for u, _, _, c in db.get_top_active_users()) assert top[2] == 1 and top[1] >= 3 # --------------------------------------------------------------------------- # Очередь и воркер # --------------------------------------------------------------------------- def _run_queue(monkeypatch, env, items_behaviour): """items_behaviour: список (FakeMessage, поведение fetch: Exception | bytes).""" by_url = {} msgs = [] for i, (msg, behaviour) in enumerate(items_behaviour): msg.text = f'https://vk.com/video-1_{i}' by_url[msg.text] = behaviour msgs.append(msg) async def fake_fetch(source, url, chat_id): b = by_url[url] if isinstance(b, Exception): raise b p = env.video / f'{chat_id}_{url[-1]}.mp4' p.write_bytes(b) return str(p), 'Title' monkeypatch.setattr(bot, 'fetch_from_service', fake_fetch) async def go(): bot.download_queue = asyncio.Queue() bot.queue_lock = asyncio.Lock() for m in msgs: await _send(m) worker = asyncio.create_task(bot.queue_worker()) await asyncio.wait_for(bot.download_queue.join(), timeout=10) worker.cancel() asyncio.run(go()) return msgs def test_worker_continues_after_timeout(env, monkeypatch): first = FakeMessage(user_id=1) second = FakeMessage(user_id=2) _run_queue(monkeypatch, env, [ (first, bot.DownloadError('timeout', 'VK: таймаут')), (second, b'video-bytes'), ]) assert first.videos == [] assert second.videos and second.videos[0]['video'] == b'video-bytes' assert 'Title' in second.videos[0]['caption'] assert bot.queue_items == [] assert list(env.video.iterdir()) == [], 'файлы после отправки удаляются' assert db.get_service_stats_7d() == {'vk': (1, 2)} assert db.get_total_downloads() == 1 def test_worker_error_message_shown_to_user(env, monkeypatch): msg = FakeMessage(lang='en') _run_queue(monkeypatch, env, [(msg, bot.DownloadError('private_or_removed', 'x'))]) expected = bot.user_error_text('en', 'vk', bot.DownloadError('private_or_removed', 'x')) shown = msg.replies + [t for st in msg.status_msgs for t in st.edits] assert expected in shown assert msg.videos == [] assert db._run('select ok, error_code from events', fetch='all') == [(0, 'private_or_removed')] def test_worker_survives_unexpected_exception(env, monkeypatch): a, b = FakeMessage(user_id=1), FakeMessage(user_id=2) _run_queue(monkeypatch, env, [(a, RuntimeError('boom')), (b, b'ok')]) assert b.videos assert db._run('select error_code from events where ok=0', fetch='all') == [('download_failed',)] def test_worker_group_success_deletes_original(env, monkeypatch): msg = FakeMessage(chat_type='supergroup', chat_id=-100) _run_queue(monkeypatch, env, [(msg, b'v')]) assert msg.videos and msg.deleted assert 'tg://user?id=42' in msg.videos[0]['caption'] # оригинал удаляется, поэтому видео не ответом — иначе цитата «Удалённое сообщение» assert msg.videos[0]['quote'] is False assert msg.videos[0]['message_thread_id'] is None def test_worker_group_topic_keeps_thread(env, monkeypatch): msg = FakeMessage(chat_type='supergroup', chat_id=-100, thread_id=77) _run_queue(monkeypatch, env, [(msg, b'v')]) assert msg.videos[0]['quote'] is False assert msg.videos[0]['message_thread_id'] == 77 def test_worker_private_deletes_link_without_quote(env, monkeypatch): msg = FakeMessage() _run_queue(monkeypatch, env, [(msg, b'v')]) assert msg.videos[0]['quote'] is False and msg.deleted def test_worker_error_keeps_link(env, monkeypatch): msg = FakeMessage() _run_queue(monkeypatch, env, [(msg, bot.DownloadError('private_or_removed', 'x'))]) assert not msg.deleted def test_worker_rejects_oversized_file(env, monkeypatch): monkeypatch.setattr(bot, 'MAX_VIDEO_SIZE', 3) msg = FakeMessage() _run_queue(monkeypatch, env, [(msg, b'four')]) assert msg.videos == [] assert db._run('select error_code from events', fetch='all') == [('too_large',)] assert list(env.video.iterdir()) == [] # --------------------------------------------------------------------------- # Алерты админу # --------------------------------------------------------------------------- def test_admin_alert_silent_codes_and_window(env, monkeypatch): sent = [] async def fake_send(text, **kw): sent.append(text) monkeypatch.setattr(bot, '_admin_send', fake_send) async def go(): for code in ('private_or_removed', 'too_large', 'sensitive_content', 'unsupported_url', 'bad_request'): await bot.notify_admin_error('youtube', 'u', bot.DownloadError(code, 'x')) await bot.notify_admin_error('youtube', 'u', bot.DownloadError('login_required', 'x')) await bot.notify_admin_error('youtube', 'u', bot.DownloadError('login_required', 'x')) await bot.notify_admin_error('vk', 'u', bot.DownloadError('login_required', 'x')) asyncio.run(go()) assert len(sent) == 2 assert '<b>x</b>' in sent[0] # --------------------------------------------------------------------------- # Cookie health-check: гистерезис, напоминание, восстановление # --------------------------------------------------------------------------- def _health_run(monkeypatch, responses): """responses: {'youtube': dict | Exception, 'instagram': ...}; возвращает отправленные алерты.""" sent = [] async def fake_send(text, **kw): sent.append(text) monkeypatch.setattr(bot, '_admin_send', fake_send) def handler(request): svc = 'youtube' if str(request.url).startswith(bot.SERVICES['youtube']['url']) else 'instagram' r = responses[svc] if isinstance(r, Exception): raise r return httpx.Response(200, json=r) mock_http(monkeypatch, handler) asyncio.run(bot.check_cookies_health()) return sent INVALID = {'status': 'cookies_invalid', 'detail': 'no longer valid', 'test_url': 'https://y/t'} OK = {'status': 'ok', 'detail': '', 'test_url': 'https://y/t'} NO = {'status': 'no_cookies'} def test_cookie_health_hysteresis_and_recovery(env, monkeypatch): assert _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) == [] # 1/2 — ждём sent = _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) # 2/2 — алерт assert len(sent) == 1 and 'cookies протухли' in sent[0] assert _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) == [] # без спама sent = _health_run(monkeypatch, {'youtube': OK, 'instagram': NO}) assert len(sent) == 1 and 'снова работает' in sent[0] assert _health_run(monkeypatch, {'youtube': OK, 'instagram': NO}) == [] def test_cookie_health_single_failure_resets(env, monkeypatch): _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) _health_run(monkeypatch, {'youtube': OK, 'instagram': NO}) assert _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) == [] def test_cookie_health_network_error_keeps_state(env, monkeypatch): _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) _health_run(monkeypatch, {'youtube': httpx.ConnectError('down'), 'instagram': NO}) sent = _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) assert len(sent) == 1, 'сетевая ошибка не должна сбрасывать счётчик неудач' def test_cookie_health_daily_reminder(env, monkeypatch): for _ in range(2): _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) state = json.loads(bot.COOKIE_STATUS_FILE.read_text()) state['last_reminder_ts']['youtube'] -= bot.COOKIE_REMINDER_INTERVAL + 1 bot.COOKIE_STATUS_FILE.write_text(json.dumps(state)) sent = _health_run(monkeypatch, {'youtube': INVALID, 'instagram': NO}) assert len(sent) == 1 and 'Сломано уже' in sent[0] def test_cookie_health_legacy_format(env, monkeypatch): for _ in range(2): sent = _health_run(monkeypatch, {'youtube': NO, 'instagram': {'cookies_valid': False}}) assert len(sent) == 1 and 'Instagram' in sent[0]