All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 2m1s
Загрузчики:
- общий downloader_common (make_app): единый /download/stream, контракт
ошибок {error, code}, X-Video-Title, workdir на запрос, потоковая отдача
- лимит 50 МБ до скачивания, noplaylist, killpg для зависших yt-dlp
- YouTube до 720p (tv_embedded → web,android → без кук), бюджет 300 с
- gunicorn gthread + семафор, конечные таймауты, healthcheck
- Yapfiles: разбор direct_link, страница входа → login_required
Бот:
- одна fetch_from_service вместо пяти, db.py (WAL, events)
- ошибки по классам и по-русски, очередь с «впереди N», лимит 3 на пользователя
- подпись с названием и автором; ссылка удаляется, видео не ответом —
без цитаты «Удалённое сообщение»
- токен не пишется в лог, удалён мёртвый код выбора качества и broadcast.py
- admin_bot: /stat в HTML, тихие и сгруппированные алерты, гистерезис кук,
рассылка с предпросмотром и только в личные чаты
Инфра: ротация логов, один образ на bot и admin_bot, теги SHA + latest,
gzip при передаче на прод. Тесты: 454 pytest, смоук на 18 проверок.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
859 lines
42 KiB
Python
859 lines
42 KiB
Python
"""Интеграционные тесты пяти Flask-сервисов (test_client, сеть и yt-dlp замоканы).
|
||
|
||
Контракт (downloader_common/app_factory.py): ошибки — JSON {error, code};
|
||
bad_request/unsupported_url 400, private_or_removed/login_required/sensitive_content 422,
|
||
too_large 413, timeout 504, download_failed 500.
|
||
"""
|
||
import json
|
||
import subprocess
|
||
from pathlib import Path
|
||
from urllib.parse import unquote
|
||
|
||
import pytest
|
||
import requests
|
||
|
||
from conftest import load_service
|
||
from downloader_common import app_factory
|
||
from downloader_common.app_factory import DownloadError, classify_error
|
||
|
||
SERVICES = ['youtube', 'instagram', 'vk', 'tiktok', 'yapfiles']
|
||
VALID_URL = {
|
||
'youtube': 'https://www.youtube.com/watch?v=jNQXAC9IVRw',
|
||
'instagram': 'https://www.instagram.com/reel/Dak0fDTMv_i/',
|
||
'vk': 'https://vk.com/video-77521_162222515',
|
||
'tiktok': 'https://www.tiktok.com/@scout2015/video/6718335390845095173',
|
||
'yapfiles': 'https://www.yapfiles.ru/show/3532099/30faa897f5a34bb58c018f909a6f1fae.mp4.html',
|
||
}
|
||
DOMAIN = {'youtube': 'youtube.com', 'instagram': 'instagram.com', 'vk': 'vk.com',
|
||
'tiktok': 'tiktok.com', 'yapfiles': 'yapfiles.ru'}
|
||
EXPECTED_STATUS = {'bad_request': 400, 'unsupported_url': 400, 'private_or_removed': 422,
|
||
'login_required': 422, 'sensitive_content': 422, 'too_large': 413,
|
||
'timeout': 504, 'download_failed': 500}
|
||
TITLE = 'Тест «видео» №1 & 100%'
|
||
PAYLOAD = b'\x00\x00\x00\x18ftypmp42' + b'x' * 4096
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Фейки загрузчиков
|
||
# ---------------------------------------------------------------------------
|
||
|
||
class Behaviour:
|
||
"""Сценарий для одной попытки скачивания."""
|
||
|
||
def __init__(self, kind='ok', message='', title=TITLE, data=PAYLOAD, ext='.mp4'):
|
||
self.kind, self.message, self.title, self.data, self.ext = kind, message, title, data, ext
|
||
|
||
|
||
def make_fake_ydl(script, calls):
|
||
"""Фейк yt_dlp.YoutubeDL: каждый __init__ берёт следующий Behaviour из script."""
|
||
|
||
class FakeYDL:
|
||
def __init__(self, opts):
|
||
self.opts = opts
|
||
self.b = script.pop(0) if len(script) > 1 else script[0]
|
||
calls.append(opts)
|
||
|
||
def __enter__(self):
|
||
return self
|
||
|
||
def __exit__(self, *a):
|
||
return False
|
||
|
||
def extract_info(self, url, download=True):
|
||
workdir = Path(self.opts['outtmpl']).parent if 'outtmpl' in self.opts else None
|
||
b = self.b
|
||
if b.kind == 'raise':
|
||
import yt_dlp
|
||
raise yt_dlp.utils.DownloadError(b.message)
|
||
if b.kind == 'too_large_log':
|
||
self.opts['logger'].info('[download] File is larger than max-filesize '
|
||
'(60000000 bytes > 52428800 bytes). Aborting.')
|
||
return {'title': b.title}
|
||
if b.kind == 'timeout':
|
||
raise TimeoutError('The read operation timed out')
|
||
if download and workdir is not None:
|
||
(workdir / f'video_abc{b.ext}').write_bytes(b.data)
|
||
(workdir / 'video_abc.f137.mp4.part').write_bytes(b'partial')
|
||
return {'title': b.title}
|
||
|
||
return FakeYDL
|
||
|
||
|
||
def make_fake_run_ytdlp(script, calls):
|
||
"""Фейк downloader_common.run_ytdlp для YouTube (CLI)."""
|
||
|
||
def fake(args, timeout):
|
||
calls.append(list(args))
|
||
b = script.pop(0) if len(script) > 1 else script[0]
|
||
if b.kind == 'timeout':
|
||
raise DownloadError(f'Превышен таймаут скачивания ({timeout}с)', 'timeout')
|
||
if b.kind == 'raise':
|
||
return 1, '', b.message
|
||
if b.kind == 'too_large_log':
|
||
return 0, '[download] File is larger than max-filesize (60000000 bytes > 52428800 bytes). Aborting.\n', ''
|
||
if b.kind == 'stderr_ok': # rc=0, но с предупреждением в stderr
|
||
return 0, '{}', b.message
|
||
if '-o' in args:
|
||
out = Path(args[args.index('-o') + 1]).parent
|
||
(out / f'video_abc{b.ext}').write_bytes(b.data)
|
||
return 0, f'[download] done\n__TITLE__{b.title}\n', ''
|
||
|
||
return fake
|
||
|
||
|
||
class FakeHTTPResponse:
|
||
def __init__(self, status=200, text='', headers=None, data=b'', exc=None):
|
||
self.status_code, self.text, self.headers, self._data = status, text, headers or {}, data
|
||
|
||
def raise_for_status(self):
|
||
if self.status_code >= 400:
|
||
raise requests.HTTPError(f'{self.status_code} Client Error')
|
||
|
||
def iter_content(self, chunk_size=1):
|
||
for i in range(0, len(self._data), chunk_size):
|
||
yield self._data[i:i + chunk_size]
|
||
|
||
def __enter__(self):
|
||
return self
|
||
|
||
def __exit__(self, *a):
|
||
return False
|
||
|
||
|
||
YAP_PAGE = '<html><video><source src="https://www.yapfiles.ru/files/1/clip.mp4?token=t"></video></html>'
|
||
|
||
|
||
def make_fake_requests_get(script, calls):
|
||
"""script: список Behaviour для запроса файла; страница всегда отдаётся YAP_PAGE."""
|
||
|
||
def fake(url, headers=None, timeout=None, stream=False):
|
||
calls.append((url, stream, timeout))
|
||
if not stream:
|
||
return FakeHTTPResponse(text=YAP_PAGE)
|
||
b = script.pop(0) if len(script) > 1 else script[0]
|
||
if b.kind == 'connect_timeout':
|
||
raise requests.exceptions.ConnectTimeout('Connection to www.yapfiles.ru timed out')
|
||
if b.kind == 'ssl_eof':
|
||
raise requests.exceptions.SSLError("EOF occurred in violation of protocol (_ssl.c:1006)")
|
||
if b.kind == 'html':
|
||
return FakeHTTPResponse(headers={'Content-Type': 'text/html'}, data=b'<html>')
|
||
if b.kind == 'big':
|
||
return FakeHTTPResponse(headers={'Content-Type': 'video/mp4',
|
||
'Content-Length': str(60 * 1024 * 1024)}, data=b'x')
|
||
if b.kind == 'http404':
|
||
return FakeHTTPResponse(status=404)
|
||
return FakeHTTPResponse(headers={'Content-Type': 'video/mp4'}, data=b.data)
|
||
|
||
return fake
|
||
|
||
|
||
@pytest.fixture
|
||
def service(request, downloads_dir, monkeypatch, tmp_path):
|
||
"""(name, flask_client, script, calls): script — изменяемый список Behaviour."""
|
||
name = request.param
|
||
mod = load_service(name)
|
||
script, calls = [Behaviour()], []
|
||
if name == 'youtube':
|
||
monkeypatch.setattr(mod, 'run_ytdlp', make_fake_run_ytdlp(script, calls))
|
||
monkeypatch.setattr(mod, 'COOKIES_FILE', tmp_path / 'absent.txt')
|
||
elif name == 'yapfiles':
|
||
monkeypatch.setattr(mod.requests, 'get', make_fake_requests_get(script, calls))
|
||
monkeypatch.setattr(mod.time, 'sleep', lambda s: None)
|
||
else:
|
||
monkeypatch.setattr(mod.yt_dlp, 'YoutubeDL', make_fake_ydl(script, calls))
|
||
if name == 'instagram':
|
||
monkeypatch.setattr(mod, 'COOKIES_FILE', tmp_path / 'absent.txt')
|
||
mod.app.config['TESTING'] = True
|
||
return name, mod.app.test_client(), script, calls
|
||
|
||
|
||
def _post(client, payload=None, raw=None, content_type='application/json'):
|
||
if raw is not None:
|
||
return client.post('/download/stream', data=raw, content_type=content_type)
|
||
return client.post('/download/stream', json=payload)
|
||
|
||
|
||
def _assert_error(resp, code):
|
||
assert resp.status_code == EXPECTED_STATUS[code], resp.get_data(as_text=True)
|
||
body = resp.get_json()
|
||
assert isinstance(body, dict) and set(body) == {'error', 'code'}, body
|
||
assert body['code'] == code, body
|
||
assert isinstance(body['error'], str) and body['error']
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# /health
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_health(service):
|
||
name, client, *_ = service
|
||
resp = client.get('/health')
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert body['status'] == 'ok' and body['service'] == name and 'yt_dlp' in body
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Контракт невалидных входов
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def _invalid_inputs(name):
|
||
d = DOMAIN[name]
|
||
return [
|
||
('пустое тело json', dict(raw=b''), 'bad_request'),
|
||
('не JSON', dict(raw=b'not json'), 'bad_request'),
|
||
('JSON без Content-Type', dict(raw=b'{"url": "x"}', content_type='text/plain'), 'bad_request'),
|
||
('массив', dict(payload=[1, 2]), 'bad_request'),
|
||
('без url', dict(payload={'foo': 'bar'}), 'bad_request'),
|
||
('url число', dict(payload={'url': 123}), 'bad_request'),
|
||
('url null', dict(payload={'url': None}), 'bad_request'),
|
||
('url пустой', dict(payload={'url': ' '}), 'bad_request'),
|
||
('чужой домен', dict(payload={'url': 'https://example.com/v'}), 'unsupported_url'),
|
||
('домен-двойник', dict(payload={'url': f'https://{d}.evil.io/v'}), 'unsupported_url'),
|
||
('префикс-двойник', dict(payload={'url': f'https://not{d}/v'}), 'unsupported_url'),
|
||
('userinfo-трюк', dict(payload={'url': f'https://{d}@evil.io/v'}), 'unsupported_url'),
|
||
('ftp', dict(payload={'url': f'ftp://{d}/v'}), 'unsupported_url'),
|
||
('javascript:', dict(payload={'url': 'javascript:alert(1)'}), 'unsupported_url'),
|
||
('без схемы', dict(payload={'url': f'{d}/v'}), 'unsupported_url'),
|
||
]
|
||
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_invalid_inputs(service, downloads_dir):
|
||
name, client, _, calls = service
|
||
for label, kwargs, code in _invalid_inputs(name):
|
||
resp = _post(client, **kwargs)
|
||
try:
|
||
_assert_error(resp, code)
|
||
except AssertionError as e:
|
||
raise AssertionError(f'{name}: {label}: {e}') from None
|
||
assert calls == [], 'на невалидный вход загрузчик вызываться не должен'
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_get_method_not_allowed_is_json(service):
|
||
_, client, *_ = service
|
||
resp = client.get('/download/stream')
|
||
assert resp.status_code == 405
|
||
body = resp.get_json()
|
||
assert body and set(body) == {'error', 'code'}
|
||
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_subdomain_and_case_allowed(service):
|
||
name, client, *_ = service
|
||
url = VALID_URL[name].replace('://www.', '://').replace('https://', 'HTTPS://M.') \
|
||
if name != 'yapfiles' else VALID_URL[name].upper().replace('/SHOW/', '/show/')
|
||
resp = _post(client, {'url': url})
|
||
assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Успешное скачивание
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_success_contract(service, downloads_dir):
|
||
name, client, *_ = service
|
||
resp = _post(client, {'url': VALID_URL[name]})
|
||
assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
|
||
data = resp.get_data()
|
||
assert data == PAYLOAD
|
||
assert resp.headers['Content-Length'] == str(len(PAYLOAD))
|
||
assert resp.headers['Content-Type'] == 'video/mp4'
|
||
cd = resp.headers['Content-Disposition']
|
||
assert cd.startswith('attachment; filename="') and cd.endswith('.mp4"')
|
||
cd.encode('ascii') # заголовок обязан быть ASCII
|
||
title = unquote(resp.headers['X-Video-Title'])
|
||
if name == 'yapfiles':
|
||
assert title == 'clip' # yapfiles берёт имя файла
|
||
else:
|
||
assert title == TITLE
|
||
resp.close()
|
||
assert list(downloads_dir.iterdir()) == [], 'workdir должен быть удалён после отдачи'
|
||
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_workdir_removed_when_client_aborts_mid_stream(service, downloads_dir, monkeypatch):
|
||
name, client, script, _ = service
|
||
monkeypatch.setattr(app_factory, 'STREAM_CHUNK', 1024)
|
||
script[0] = Behaviour(data=b'y' * 10_000)
|
||
resp = client.post('/download/stream', json={'url': VALID_URL[name]}, buffered=False)
|
||
assert resp.status_code == 200
|
||
it = iter(resp.response)
|
||
next(it)
|
||
resp.close()
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_bot_parses_service_headers(service):
|
||
"""Сквозной контракт: бот извлекает title/расширение из заголовков фабрики."""
|
||
import bot
|
||
name, client, *_ = service
|
||
resp = _post(client, {'url': VALID_URL[name]})
|
||
title = bot._title_from_headers(resp.headers)
|
||
assert title == (TITLE if name != 'yapfiles' else 'clip')
|
||
fn = bot._parse_content_disposition(resp.headers['Content-Disposition'])
|
||
assert bot._pick_extension(resp.headers['Content-Type'], fn) == 'mp4'
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Ошибки скачивания
|
||
# ---------------------------------------------------------------------------
|
||
|
||
YTDLP_ERRORS = [
|
||
("ERROR: [x] abc: Private video. Sign in if you've been granted access to this video", 'private_or_removed'),
|
||
('ERROR: [x] abc: Video unavailable. This video has been removed by the uploader', 'private_or_removed'),
|
||
("ERROR: [x] abc: Sign in to confirm you're not a bot", 'login_required'),
|
||
("ERROR: [Instagram] abc: This content can't be seen by certain audiences", 'sensitive_content'),
|
||
('ERROR: Unable to download webpage: The read operation timed out', 'timeout'),
|
||
('ERROR: [x] abc: something exploded', 'download_failed'),
|
||
]
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube', 'instagram', 'vk', 'tiktok'], indirect=True)
|
||
@pytest.mark.parametrize('message, code', YTDLP_ERRORS)
|
||
def test_ytdlp_error_mapping(service, downloads_dir, message, code):
|
||
name, client, script, _ = service
|
||
script[0] = Behaviour('raise', message)
|
||
resp = _post(client, {'url': VALID_URL[name]})
|
||
_assert_error(resp, code)
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube', 'instagram', 'vk', 'tiktok'], indirect=True)
|
||
def test_too_large_by_log_marker(service, downloads_dir):
|
||
"""yt-dlp молча пропускает файл > max-filesize — маркер в логе → 413."""
|
||
name, client, script, _ = service
|
||
script[0] = Behaviour('too_large_log')
|
||
resp = _post(client, {'url': VALID_URL[name]})
|
||
_assert_error(resp, 'too_large')
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_too_large_by_size(service, downloads_dir, monkeypatch):
|
||
name, client, *_ = service
|
||
monkeypatch.setattr(app_factory, 'MAX_FILESIZE', 1000)
|
||
resp = _post(client, {'url': VALID_URL[name]})
|
||
_assert_error(resp, 'too_large')
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', SERVICES, indirect=True)
|
||
def test_empty_file_is_download_failed(service, downloads_dir):
|
||
name, client, script, _ = service
|
||
script[0] = Behaviour(data=b'')
|
||
resp = _post(client, {'url': VALID_URL[name]})
|
||
_assert_error(resp, 'download_failed')
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['instagram', 'vk', 'tiktok'], indirect=True)
|
||
def test_python_timeout_is_504(service):
|
||
name, client, script, _ = service
|
||
script[0] = Behaviour('timeout')
|
||
_assert_error(_post(client, {'url': VALID_URL[name]}), 'timeout')
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# YouTube: ретрай без кук, мастер-файл кук, /formats, /cookies/check
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.fixture
|
||
def yt_cookies(tmp_path, monkeypatch):
|
||
mod = load_service('youtube')
|
||
master = tmp_path / 'youtube_cookies.txt'
|
||
master.write_text('# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t0\tSID\tmaster\n')
|
||
scratch = tmp_path / 'scratch.txt'
|
||
monkeypatch.setattr(mod, 'COOKIES_FILE', master)
|
||
monkeypatch.setattr(mod, 'COOKIES_SCRATCH', scratch)
|
||
return master, scratch
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
def test_youtube_retry_without_cookies(service, yt_cookies, downloads_dir):
|
||
"""72ba00b: если всё с куками падает — последняя попытка без --cookies; yt-dlp видит только scratch."""
|
||
master, scratch = yt_cookies
|
||
name, client, script, calls = service
|
||
ok = make_fake_run_ytdlp([Behaviour()], [])
|
||
|
||
def fake(args, timeout):
|
||
calls.append(list(args))
|
||
if '--cookies' in args:
|
||
return 1, '', 'ERROR: [youtube] abc: HTTP Error 403: Forbidden'
|
||
return ok(args, timeout)
|
||
load_service('youtube').run_ytdlp = fake
|
||
resp = _post(client, {'url': VALID_URL['youtube']})
|
||
assert resp.status_code == 200, resp.get_data(as_text=True)
|
||
resp.get_data()
|
||
with_cookies = [c for c in calls if '--cookies' in c]
|
||
assert with_cookies, 'при наличии кук первая попытка — с куками'
|
||
assert '--cookies' in calls[0]
|
||
for c in with_cookies:
|
||
assert c[c.index('--cookies') + 1] == str(scratch)
|
||
assert str(master) not in c, 'yt-dlp не должен видеть мастер-файл (c9972f3)'
|
||
assert '--cookies' not in calls[-1]
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
def test_youtube_master_cookies_untouched(service, yt_cookies):
|
||
master, scratch = yt_cookies
|
||
before = master.read_bytes()
|
||
_, client, script, calls = service
|
||
|
||
def clobber(args, timeout): # yt-dlp переписывает свой cookie jar
|
||
if '--cookies' in args:
|
||
Path(args[args.index('--cookies') + 1]).write_text('# wiped\n')
|
||
return 1, '', 'ERROR: boom'
|
||
load_service('youtube').run_ytdlp = clobber
|
||
try:
|
||
_post(client, {'url': VALID_URL['youtube']})
|
||
finally:
|
||
pass
|
||
assert master.read_bytes() == before
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
@pytest.mark.parametrize('message', [
|
||
"ERROR: [youtube] abc: This content can't be seen by certain audiences",
|
||
'[download] File is larger than max-filesize (60000000 bytes > 52428800 bytes)',
|
||
])
|
||
def test_youtube_no_second_attempt_for_final_errors(service, yt_cookies, message):
|
||
_, client, script, calls = service
|
||
script[:] = [Behaviour('raise', message)]
|
||
_post(client, {'url': VALID_URL['youtube']})
|
||
assert len(calls) == 1
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
def test_youtube_both_attempts_fail_reports_last_stderr(service, yt_cookies):
|
||
_, client, script, calls = service
|
||
script[:] = [Behaviour('raise', 'ERROR: first'), Behaviour('raise', 'ERROR: [youtube] x: Video unavailable')]
|
||
resp = _post(client, {'url': VALID_URL['youtube']})
|
||
_assert_error(resp, 'private_or_removed')
|
||
assert 'Video unavailable' in resp.get_json()['error']
|
||
assert len(calls) >= 2
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
def test_youtube_cli_timeout_is_504(service):
|
||
_, client, script, calls = service
|
||
script[0] = Behaviour('timeout')
|
||
_assert_error(_post(client, {'url': VALID_URL['youtube']}), 'timeout')
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
def test_youtube_cli_args(service):
|
||
"""67dba21: разделитель extractor-args — ';', JS-рантайм deno, лимит размера."""
|
||
_, client, _, calls = service
|
||
_post(client, {'url': VALID_URL['youtube']}).get_data()
|
||
args = calls[0]
|
||
ea = args[args.index('--extractor-args') + 1]
|
||
import re
|
||
assert re.fullmatch(r'youtube:player_client=[a-z_]+(,[a-z_]+)*;skip=[a-z_,]+', ea), ea
|
||
assert args[args.index('--js-runtimes') + 1] == 'deno'
|
||
assert args[args.index('--max-filesize') + 1] == str(50 * 1024 * 1024)
|
||
assert '--no-playlist' in args
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
def test_youtube_formats_endpoint(service):
|
||
_, client, script, _ = service
|
||
assert client.post('/formats', json={}).status_code == 400
|
||
assert client.post('/formats', data=b'x', content_type='application/json').status_code == 400
|
||
load = load_service('youtube')
|
||
info = {'formats': [{'format_id': '18', 'ext': 'mp4', 'height': 360, 'vcodec': 'avc1', 'filesize': 1048576},
|
||
{'format_id': '140', 'vcodec': 'none'}]}
|
||
load.run_ytdlp = lambda args, timeout: (0, json.dumps(info), '')
|
||
resp = client.post('/formats', json={'url': VALID_URL['youtube']})
|
||
assert resp.status_code == 200
|
||
assert resp.get_json()['formats'] == [{'format_id': '18', 'ext': 'mp4', 'height': 360,
|
||
'label': '360p', 'filesize_mb': 1.0}]
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
@pytest.mark.parametrize('rc, stderr, status', [
|
||
(0, '', 'ok'),
|
||
(0, 'WARNING: [youtube] The provided YouTube account cookies are no longer valid. '
|
||
'They have likely been rotated in the browser as a security measure', 'cookies_invalid'),
|
||
(1, "ERROR: [youtube] x: Sign in to confirm you're not a bot", 'cookies_invalid'),
|
||
(1, 'ERROR: [youtube] x: n challenge solving failed', 'extraction_failed'),
|
||
])
|
||
def test_youtube_cookies_check(service, yt_cookies, rc, stderr, status):
|
||
_, client, *_ = service
|
||
load_service('youtube').run_ytdlp = lambda args, timeout: (rc, '{}', stderr)
|
||
body = client.post('/cookies/check').get_json()
|
||
assert body['status'] == status
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['youtube'], indirect=True)
|
||
def test_youtube_cookies_check_no_file(service):
|
||
_, client, *_ = service
|
||
assert client.post('/cookies/check').get_json()['status'] == 'no_cookies'
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Instagram: fallback без кук, /cookies/check
|
||
# ---------------------------------------------------------------------------
|
||
|
||
IG_COOKIES = ('# Netscape HTTP Cookie File\n'
|
||
'.instagram.com\tTRUE\t/\tTRUE\t0\tcsrftoken\tCSRF\n'
|
||
'.instagram.com\tTRUE\t/\tTRUE\t0\tsessionid\tSESS\n')
|
||
|
||
|
||
@pytest.fixture
|
||
def ig_cookies(tmp_path, monkeypatch):
|
||
mod = load_service('instagram')
|
||
master = tmp_path / 'instagram_cookies.txt'
|
||
master.write_text(IG_COOKIES)
|
||
scratch = tmp_path / 'ig_scratch.txt'
|
||
monkeypatch.setattr(mod, 'COOKIES_FILE', master)
|
||
monkeypatch.setattr(mod, 'COOKIES_SCRATCH', scratch)
|
||
return master, scratch
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['instagram'], indirect=True)
|
||
def test_instagram_fallback_without_cookies(service, ig_cookies, downloads_dir):
|
||
master, scratch = ig_cookies
|
||
_, client, script, calls = service
|
||
script[:] = [Behaviour('raise', 'ERROR: [Instagram] x: Unable to download JSON metadata: HTTP Error 404'),
|
||
Behaviour()]
|
||
resp = _post(client, {'url': VALID_URL['instagram']})
|
||
assert resp.status_code == 200
|
||
resp.get_data()
|
||
assert calls[0]['cookiefile'] == str(scratch)
|
||
assert 'cookiefile' not in calls[1]
|
||
assert master.read_text() == IG_COOKIES
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['instagram'], indirect=True)
|
||
def test_instagram_sensitive_no_retry(service, ig_cookies):
|
||
_, client, script, calls = service
|
||
script[:] = [Behaviour('raise', "ERROR: [Instagram] x: This content can't be seen by certain audiences")]
|
||
_assert_error(_post(client, {'url': VALID_URL['instagram']}), 'sensitive_content')
|
||
assert len(calls) == 1
|
||
|
||
|
||
@pytest.mark.parametrize('service', ['instagram'], indirect=True)
|
||
def test_instagram_cookies_check_states(service, tmp_path, monkeypatch, ig_cookies):
|
||
mod = load_service('instagram')
|
||
_, client, script, calls = service
|
||
master, _ = ig_cookies
|
||
|
||
script[:] = [Behaviour()]
|
||
assert client.post('/cookies/check').get_json()['status'] == 'ok'
|
||
|
||
script[:] = [Behaviour('raise', 'ERROR: 404'), Behaviour()]
|
||
body = client.post('/cookies/check').get_json()
|
||
assert body['status'] == 'ok' and body['cookies_valid'] is None and 'fallback' in body['detail']
|
||
|
||
script[:] = [Behaviour('raise', 'ERROR: a'), Behaviour('raise', 'ERROR: b')]
|
||
assert client.post('/cookies/check').get_json()['status'] == 'extraction_failed'
|
||
|
||
master.write_text('# Netscape\n.instagram.com\tTRUE\t/\tTRUE\t0\tcsrftoken\tCSRF\n')
|
||
assert client.post('/cookies/check').get_json()['status'] == 'cookies_incomplete'
|
||
|
||
monkeypatch.setattr(mod, 'COOKIES_FILE', tmp_path / 'nope.txt')
|
||
assert client.post('/cookies/check').get_json()['status'] == 'no_cookies'
|
||
|
||
|
||
def test_instagram_has_sessionid(tmp_path):
|
||
mod = load_service('instagram')
|
||
f = tmp_path / 'c.txt'
|
||
f.write_text(IG_COOKIES)
|
||
assert mod._has_instagram_sessionid(f)
|
||
f.write_text('.instagram.com\tTRUE\t/\tTRUE\t0\tcsrftoken\tx\n.facebook.com\tTRUE\t/\tTRUE\t0\tsessionid\tx\n')
|
||
assert not mod._has_instagram_sessionid(f)
|
||
assert not mod._has_instagram_sessionid(tmp_path / 'missing.txt')
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Yapfiles: разбор страницы и сетевые ошибки
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('service', ['yapfiles'], indirect=True)
|
||
@pytest.mark.parametrize('kind, code, attempts', [
|
||
('html', 'private_or_removed', 1),
|
||
('big', 'too_large', 1),
|
||
('connect_timeout', 'timeout', 2),
|
||
('ssl_eof', 'download_failed', 2),
|
||
('http404', 'download_failed', 2),
|
||
])
|
||
def test_yapfiles_errors(service, downloads_dir, kind, code, attempts):
|
||
_, client, script, calls = service
|
||
script[:] = [Behaviour(kind)]
|
||
_assert_error(_post(client, {'url': VALID_URL['yapfiles']}), code)
|
||
assert sum(1 for _, stream, _ in calls if stream) == attempts
|
||
assert all(t is not None for _, _, t in calls), 'requests без таймаута держит воркер вечно'
|
||
assert list(downloads_dir.iterdir()) == []
|
||
|
||
|
||
@pytest.mark.parametrize('html_text, page_url, expected', [
|
||
(YAP_PAGE, 'https://www.yapfiles.ru/show/1/x.mp4.html', 'https://www.yapfiles.ru/files/1/clip.mp4?token=t'),
|
||
('<a href="/files/2/b.mp4?token=z">dl</a>', 'https://www.yapfiles.ru/show/2/b.mp4.html',
|
||
'https://www.yapfiles.ru/files/2/b.mp4?token=z'),
|
||
('<script>var u="https://cdn.yapfiles.ru/files/3/c.mp4?token=q";</script>', 'https://www.yapfiles.ru/x',
|
||
'https://cdn.yapfiles.ru/files/3/c.mp4?token=q'),
|
||
('<html></html>', 'https://www.yapfiles.ru/show/3532099/30faa.mp4.html',
|
||
'https://www.yapfiles.ru/files/3532099/30faa.mp4'),
|
||
# реальная разметка 2026-10: ссылка только в поле «Прямая ссылка», токен после hq=1
|
||
('<input type="text" name="direct_link" value="https://www.yapfiles.ru/files/4/d.mp4?hq=1&token=T">'
|
||
'<script>escape(\'https://www.yapfiles.ru/files/4/d.mp4?hq=1&token=T\')</script>',
|
||
'https://www.yapfiles.ru/show/4/d.mp4.html', 'https://www.yapfiles.ru/files/4/d.mp4?hq=1&token=T'),
|
||
])
|
||
def test_yapfiles_extract_download_url(monkeypatch, html_text, page_url, expected):
|
||
mod = load_service('yapfiles')
|
||
monkeypatch.setattr(mod.requests, 'get', lambda *a, **k: FakeHTTPResponse(text=html_text))
|
||
url, filename = mod.extract_download_url(page_url)
|
||
assert url == expected
|
||
assert filename.endswith('.mp4') or filename == 'yapfiles_video.mp4'
|
||
|
||
|
||
def test_yapfiles_no_link_is_422(monkeypatch):
|
||
mod = load_service('yapfiles')
|
||
monkeypatch.setattr(mod.requests, 'get', lambda *a, **k: FakeHTTPResponse(text='<html></html>'))
|
||
with pytest.raises(DownloadError) as e:
|
||
mod.extract_download_url('https://www.yapfiles.ru/user/abc')
|
||
assert e.value.code == 'private_or_removed'
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# classify_error на реальных строках yt-dlp 2026.10.21
|
||
# ---------------------------------------------------------------------------
|
||
|
||
YT_COOKIE_HINT = ('Use --cookies-from-browser or --cookies for the authentication. See '
|
||
'https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp for how to manually '
|
||
'pass cookies. Also see https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies '
|
||
'for tips on effectively exporting YouTube cookies')
|
||
|
||
REAL_ERRORS = [
|
||
# приватное / удалённое
|
||
("ERROR: [youtube] abc: Private video. Sign in if you've been granted access to this video",
|
||
'private_or_removed'),
|
||
('ERROR: [youtube] abc: Video unavailable', 'private_or_removed'),
|
||
('ERROR: [youtube] abc: Video unavailable. This video has been removed by the uploader', 'private_or_removed'),
|
||
('ERROR: [vk] -1_1: Video -1_1 does not exist.', 'private_or_removed'),
|
||
('ERROR: [TikTok] 1: Video not available, status code 10204', 'private_or_removed'),
|
||
('ERROR: [vk] -1_2: Video -1_2 is temporarily unavailable.', 'private_or_removed'),
|
||
# логин / куки
|
||
# Приватное YouTube: yt-dlp дописывает к «Sign in if you've been granted access» подсказку про
|
||
# --cookies — раньше маркер 'cookies' давал login_required (ложный алерт «куки протухли»).
|
||
("ERROR: [youtube] abc: Private video. Sign in if you've been granted access to this video. "
|
||
+ YT_COOKIE_HINT, 'private_or_removed'),
|
||
("ERROR: [youtube] abc: Sign in to confirm you’re not a bot. " + YT_COOKIE_HINT, 'login_required'),
|
||
('ERROR: [youtube] abc: Sign in to confirm your age. This video may be inappropriate for some users. '
|
||
+ YT_COOKIE_HINT, 'login_required'),
|
||
('ERROR: unable to download video data: HTTP Error 401: Unauthorized', 'login_required'),
|
||
# чувствительный контент Instagram
|
||
("ERROR: [Instagram] abc: This content can't be seen by certain audiences", 'sensitive_content'),
|
||
("ERROR: [Instagram] abc: This post isn't available to everyone", 'sensitive_content'),
|
||
# размер
|
||
('[download] File is larger than max-filesize (60000000 bytes > 52428800 bytes). Aborting.', 'too_large'),
|
||
# таймауты
|
||
("ERROR: Unable to download webpage: <urlopen error [Errno 110] Connection timed out> "
|
||
"(caused by URLError(TimeoutError(110, 'Connection timed out')))", 'timeout'),
|
||
('ERROR: [vk] 1: Unable to download webpage: The read operation timed out', 'timeout'),
|
||
("HTTPSConnectionPool(host='www.yapfiles.ru', port=443): Read timed out. (read timeout=30)", 'timeout'),
|
||
# прочее — наша/инфраструктурная поломка, админу нужен алерт
|
||
('ERROR: [TikTok] 123: Your IP address is blocked from accessing this post', 'download_failed'),
|
||
('ERROR: unable to download video data: HTTP Error 403: Forbidden', 'download_failed'),
|
||
("HTTPSConnectionPool(host='www.yapfiles.ru', port=443): Max retries exceeded with url: / (Caused by "
|
||
"SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1006)')))", 'download_failed'),
|
||
('ERROR: [youtube] abc: Requested format is not available. Use --list-formats for a list of available formats',
|
||
'download_failed'),
|
||
('ERROR: [youtube] abc: n challenge solving failed: Some formats may be missing', 'download_failed'),
|
||
('ERROR: [youtube] abc: No video formats found!; please report this issue', 'download_failed'),
|
||
('', 'download_failed'),
|
||
]
|
||
|
||
# Найденные баги классификатора: тест обязан падать, пока баг не исправлен.
|
||
BUGGY_ERRORS = [
|
||
# Регресс-тест после правки «private раньше login, без голого cookies».
|
||
# Instagram: лимит анонимного доступа / стена логина. После того как private_or_removed
|
||
# поставили раньше login_required, «not available ... login required» уходит в private
|
||
# (пользователю «видео приватное», админ молчит — SILENT_ADMIN_CODES), а редирект на логин —
|
||
# в download_failed (пользователь не узнаёт, что нужен вход).
|
||
('ERROR: [Instagram] abc: Requested content is not available, rate-limit reached or login required. '
|
||
'Use --cookies-from-browser or --cookies for the authentication.', 'login_required'),
|
||
('ERROR: [Instagram] abc: The webpage request was redirected to the login page. You have exceeded the '
|
||
'rate-limit for accessing posts anonymously. Use --cookies-from-browser or --cookies', 'login_required'),
|
||
# Временная 503 CDN → 'unavailable' → 422 «приватное/удалено», бот не ретраит.
|
||
('ERROR: unable to download video data: HTTP Error 503: Service Unavailable', 'download_failed'),
|
||
# Блокировка клиента YouTube (нужен апдейт yt-dlp) → 'not available' → «приватное»,
|
||
# и код в SILENT_ADMIN_CODES — поломка экстрактора скрыта от админа.
|
||
('ERROR: [youtube] abc: The following content is not available on this app. '
|
||
'Watch on the latest version of YouTube.', 'download_failed'),
|
||
# То же для приватного поста TikTok (raise_login_required + подсказка про --cookies).
|
||
('ERROR: [TikTok] 1: You do not have permission to view this post. Log into an account that has access. '
|
||
'Use --cookies-from-browser or --cookies for the authentication.', 'private_or_removed'),
|
||
# VK: удалённое видео / автор заблокирован — нет маркера 'deleted'/'no longer available'
|
||
# → download_failed: пользователь видит «попробуйте позже», админ — ложный алерт.
|
||
('ERROR: [vk] -1_2: Video -1_2 is no longer available, because it has been deleted.', 'private_or_removed'),
|
||
('ERROR: [vk] -1_2: Video -1_2 is no longer available, because its author has been blocked.',
|
||
'private_or_removed'),
|
||
# yt-dlp «Unsupported URL» (домен наш, путь не видео: youtube.com/feed, vk.com/durov)
|
||
('ERROR: Unsupported URL: https://www.youtube.com/feed/subscriptions', 'unsupported_url'),
|
||
]
|
||
|
||
|
||
def test_classify_error_instagram_empty_media_alerts_admin():
|
||
"""«empty media response» — не приватность: допустимы login_required или download_failed
|
||
(оба доходят до админа), но не private_or_removed (SILENT_ADMIN_CODES)."""
|
||
text = ('ERROR: [Instagram] abc: Instagram sent an empty media response. Check if this post is accessible '
|
||
'in your browser without being logged-in. If it is not, then use --cookies-from-browser or --cookies '
|
||
'for the authentication.')
|
||
assert classify_error(text)[0] in ('login_required', 'download_failed')
|
||
|
||
|
||
@pytest.mark.parametrize('text, expected', REAL_ERRORS)
|
||
def test_classify_error_real_strings(text, expected):
|
||
assert classify_error(text)[0] == expected
|
||
assert classify_error(text)[1] == EXPECTED_STATUS[expected]
|
||
|
||
|
||
@pytest.mark.parametrize('text, expected', BUGGY_ERRORS)
|
||
def test_classify_error_known_bugs(text, expected):
|
||
assert classify_error(text)[0] == expected
|
||
|
||
|
||
def test_classify_error_curly_apostrophe():
|
||
assert classify_error('ERROR: [Instagram] x: This content can’t be seen by certain audiences')[0] == \
|
||
'sensitive_content'
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Хелперы фабрики
|
||
# ---------------------------------------------------------------------------
|
||
|
||
@pytest.mark.parametrize('exc, code', [
|
||
(subprocess.TimeoutExpired('yt-dlp', 5), 'timeout'),
|
||
(requests.exceptions.ReadTimeout('x'), 'timeout'),
|
||
(requests.exceptions.ConnectTimeout('x'), 'timeout'),
|
||
(TimeoutError('x'), 'timeout'),
|
||
(DownloadError('x', 'too_large'), 'too_large'),
|
||
(DownloadError('Video unavailable'), 'private_or_removed'),
|
||
(RuntimeError('boom'), 'download_failed'),
|
||
])
|
||
def test_error_class(exc, code):
|
||
assert app_factory.error_class(exc)[0] == code
|
||
|
||
|
||
@pytest.mark.parametrize('url, ok', [
|
||
('https://youtube.com/x', True), ('https://www.youtube.com/x', True), ('http://m.youtube.com/x', True),
|
||
('https://YOUTUBE.COM./x', True), ('https://youtube.com:8443/x', True),
|
||
('https://notyoutube.com/x', False), ('https://youtube.com.evil.io/x', False),
|
||
('https://youtube.com@evil.io/x', False), ('ftp://youtube.com/x', False), ('youtube.com/x', False),
|
||
('https://[::1/x', False),
|
||
])
|
||
def test_host_allowed(url, ok):
|
||
assert app_factory._host_allowed(url, ('youtube.com',)) is ok
|
||
|
||
|
||
@pytest.mark.parametrize('name, expected', [
|
||
('Me at the zoo_jNQXAC9IVRw.mp4', 'Me_at_the_zoo_jNQXAC9IVRw.mp4'),
|
||
('Видео.mp4', 'vk_video.mp4'),
|
||
('Клип ok.MP4', 'ok.mp4'),
|
||
('clip.weird', 'clip.mp4'),
|
||
('a"b;c.webm', 'a_b_c.webm'),
|
||
])
|
||
def test_ascii_filename(name, expected):
|
||
assert app_factory._ascii_filename(Path(name), 'vk') == expected
|
||
|
||
|
||
def test_find_downloaded_file(tmp_path):
|
||
(tmp_path / 'a.mp4').write_bytes(b'x' * 10)
|
||
(tmp_path / 'b.f137.mp4.part').write_bytes(b'x' * 100)
|
||
(tmp_path / 'c.m4a').write_bytes(b'x' * 5)
|
||
assert app_factory.find_downloaded_file(tmp_path).name == 'a.mp4'
|
||
|
||
|
||
def test_find_downloaded_file_errors(tmp_path):
|
||
(tmp_path / 'x.part').write_bytes(b'1')
|
||
with pytest.raises(DownloadError) as e:
|
||
app_factory.find_downloaded_file(tmp_path, 'File is larger than max-filesize')
|
||
assert e.value.code == 'too_large'
|
||
with pytest.raises(DownloadError) as e:
|
||
app_factory.find_downloaded_file(tmp_path, '')
|
||
assert e.value.code == 'download_failed'
|
||
|
||
|
||
def test_run_ytdlp_kills_process_group_on_timeout():
|
||
from downloader_common.ytdlp_common import run_ytdlp
|
||
with pytest.raises(DownloadError) as e:
|
||
run_ytdlp(['sh', '-c', 'sleep 30 & sleep 30'], timeout=1)
|
||
assert e.value.code == 'timeout'
|
||
|
||
|
||
def test_ydl_opts_contract(tmp_path):
|
||
from downloader_common.ytdlp_common import base_ydl_opts
|
||
opts = base_ydl_opts(tmp_path)
|
||
assert opts['max_filesize'] == 50 * 1024 * 1024 and opts['noplaylist'] is True
|
||
assert opts['socket_timeout'] and Path(opts['outtmpl']).parent == tmp_path
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Сквозной класс ошибки: сервис (classify_error → HTTP) → бот (_error_from_response)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
E2E = [
|
||
(REAL_ERRORS[0][0], 'private_or_removed'),
|
||
("ERROR: [youtube] abc: Sign in to confirm you’re not a bot. " + YT_COOKIE_HINT, 'login_required'),
|
||
('[download] File is larger than max-filesize (60000000 bytes > 52428800 bytes). Aborting.', 'too_large'),
|
||
('ERROR: [TikTok] 123: Your IP address is blocked from accessing this post', 'download_failed'),
|
||
('ERROR: Unsupported URL: https://www.youtube.com/feed/subscriptions', 'unsupported_url'),
|
||
pytest.param('ERROR: [Instagram] abc: The webpage request was redirected to the login page. You have '
|
||
'exceeded the rate-limit for accessing posts anonymously. Use --cookies-from-browser or --cookies',
|
||
'login_required', id='bug-instagram-login-redirect-shown-as-generic'),
|
||
pytest.param('ERROR: [Instagram] abc: Requested content is not available, rate-limit reached or login '
|
||
'required. Use --cookies-from-browser or --cookies for the authentication.', 'login_required',
|
||
id='bug-instagram-login-wall-shown-as-private'),
|
||
pytest.param('ERROR: [youtube] abc: The following content is not available on this app. '
|
||
'Watch on the latest version of YouTube.', 'download_failed',
|
||
id='bug-youtube-client-blocked-shown-as-private'),
|
||
pytest.param('ERROR: unable to download video data: HTTP Error 503: Service Unavailable', 'download_failed',
|
||
id='bug-http503-shown-as-private'),
|
||
pytest.param('ERROR: [vk] -1_2: Video -1_2 is no longer available, because it has been deleted.',
|
||
'private_or_removed', id='bug-vk-deleted-shown-as-generic'),
|
||
pytest.param('ERROR: [TikTok] 1: You do not have permission to view this post. Log into an account that has '
|
||
'access. Use --cookies-from-browser or --cookies for the authentication.', 'private_or_removed',
|
||
id='bug-tiktok-private-shown-as-login'),
|
||
]
|
||
|
||
|
||
@pytest.mark.parametrize('text, expected', E2E)
|
||
def test_end_to_end_user_visible_code(text, expected):
|
||
"""То, что реально увидит пользователь и получит/не получит админ."""
|
||
import bot
|
||
code, status = classify_error(text)
|
||
body = json.dumps({'error': text, 'code': code}).encode()
|
||
assert bot._error_from_response('youtube', status, body).code == expected
|
||
|
||
|
||
YAP_LOGIN_PAGE = ('<html><head><title>ЯП файлы - Авторизация</title></head><body>'
|
||
'<a href="https://www.yapfiles.ru/login/?redirect=https://www.yapfiles.ru/show/1/x.mp4.html">'
|
||
'Вход</a><form>Имя Пароль</form></body></html>')
|
||
|
||
|
||
def test_yapfiles_login_wall_is_not_generic_500(downloads_dir, monkeypatch):
|
||
"""Смоук 2026-10-22: страница файла отдаёт форму «Авторизация» без <video>/token, сервис
|
||
угадывает /files/<id>/<name> (способ 4), CDN отвечает 403, после 2 попыток — 500
|
||
download_failed. Ожидаемо: 422 (login_required/private_or_removed) без повторов."""
|
||
mod = load_service('yapfiles')
|
||
calls = []
|
||
|
||
def fake_get(url, headers=None, timeout=None, stream=False):
|
||
calls.append(url)
|
||
if not stream:
|
||
return FakeHTTPResponse(text=YAP_LOGIN_PAGE)
|
||
return FakeHTTPResponse(status=403)
|
||
monkeypatch.setattr(mod.requests, 'get', fake_get)
|
||
monkeypatch.setattr(mod.time, 'sleep', lambda s: None)
|
||
resp = mod.app.test_client().post('/download/stream', json={'url': VALID_URL['yapfiles']})
|
||
assert resp.status_code == 422, resp.get_json()
|
||
assert resp.get_json()['code'] in ('login_required', 'private_or_removed')
|