# -*- coding: utf-8 -*- """/download 端点 json 同步模式的契约测试(沙箱,不触真实上游)。 test_download_billing.py 覆盖参数校验与退费口径;本文件钉住 format=json 的同步下载分支——它此前零覆盖,却是 40 行内嵌「取信息 → 下载 → 组响应 → 结算」的完整事务: - 任一步失败:退回预扣(无 open 账本行)+ 专属文案 - 成功:settle(1, 'delivered'),余额恰好 -1 替身边界:monkeypatch ``services.api_service.api_service.downloader`` (路由内延迟导入取的就是这个实例属性),MusicInfo/DownloadResult 用 真实 dataclass 构造。 """ import asyncio import pytest from fastapi.testclient import TestClient import auth_system as auth import core.db as db from music_downloader.models import MusicInfo SECRET = 'download-sync-test-secret' PW = 'Passw0rd12' async def _fake_secret_key() -> str: return SECRET def _info() -> MusicInfo: return MusicInfo(id=347230, name='晴天', artists='周杰伦', album='叶惠美', pic_url='', duration=269, track_number=1, download_url='', file_type='mp3', file_size=1024, quality='lossless') def _dl(success: bool = True, msg: str = ''): from music_downloader.models import DownloadResult return DownloadResult(success=success, file_path='/tmp/x.mp3', error_message=msg) @pytest.fixture() def env(tmp_path, monkeypatch): db_path = tmp_path / 'site.db' monkeypatch.setattr(auth.db, 'DATA_DIR', tmp_path) monkeypatch.setattr(auth.db, 'DB_PATH', db_path) monkeypatch.setattr(auth.db, 'BACKUP_DIR', tmp_path / 'backups') monkeypatch.setattr(auth.db, 'SECRET_KEY_PATH', tmp_path / 'secret.key') monkeypatch.setattr(db, 'DATA_DIR', tmp_path) monkeypatch.setattr(db, 'DB_PATH', db_path) asyncio.run(auth.init_db()) monkeypatch.setattr('web.deps.secret_key', _fake_secret_key) asyncio.run(auth.create_user('payer', PW, email='p@example.com', credits=3)) state: dict = {'info_exc': None, 'dl_result': _dl(), 'dl_exc': None} class _FakeDownloader: async def get_music_info(self, music_id, quality, cookies): if state['info_exc'] is not None: raise state['info_exc'] return state['info'] async def download_music_file(self, music_id, quality, **kw): if state['dl_exc'] is not None: raise state['dl_exc'] return state['dl_result'] state['info'] = _info() from services.api_service import api_service monkeypatch.setattr(api_service, 'downloader', _FakeDownloader()) from web.app import create_app client = TestClient(create_app()) r = client.post('/auth/login', json={'username': 'payer', 'password': PW}) raw = r.headers.get('set-cookie', '') cookie = '' for part in raw.split(';'): if part.strip().startswith('session='): cookie = part.strip()[len('session='):] break state['headers'] = {'Cookie': f'session={cookie}'} state['client'] = client return state def _balance(username: str = 'payer') -> int: u = asyncio.run(auth.get_user_by_name(username)) assert u is not None, f'用户 {username} 不存在' return int(u['duration_seconds'] or 0) def _open_rows() -> list[dict]: rows = asyncio.run(auth._q( "SELECT task_id, status FROM billing_ledger WHERE status='open'")) return [dict(r) for r in rows] def _post(env, **payload): return env['client'].post('/download', json={'id': '347230', 'format': 'json', **payload}, headers=env['headers']) def test_json_success_settles_one_credit(env): r = _post(env) assert r.status_code == 200 body = r.json() assert body is not None and body['success'] is True assert body['data']['name'] == '晴天' assert body['data']['artist'] == '周杰伦' assert body['data']['filename'] == '周杰伦 - 晴天.mp3' # 默认 filename_format=artist_song assert body['data']['duration'] == 269 * 1000 assert _balance() == 2 # 预扣 1,交付结算 assert _open_rows() == [] def test_json_info_failure_refunds(env): env['info_exc'] = RuntimeError('song gone') r = _post(env) assert r.status_code == 404 assert r.json()['message'] == '获取失败:歌曲不存在或暂无版权' assert _balance() == 3 assert _open_rows() == [] def test_json_download_failure_refunds(env): env['dl_result'] = _dl(success=False, msg='size mismatch') r = _post(env) assert r.status_code == 500 assert r.json()['message'] == '下载失败,请稍后重试或更换音质' assert _balance() == 3 assert _open_rows() == [] def test_json_download_exception_refunds(env): env['dl_exc'] = RuntimeError('disk full') r = _post(env) assert r.status_code == 500 assert r.json()['message'] == '服务暂时不可用,请稍后再试' assert _balance() == 3 assert _open_rows() == [] def test_empty_id_refunds_with_specific_message(env): r = env['client'].post('/download', json={'id': '', 'format': 'json'}, headers=env['headers']) assert r.json()['message'] == "参数 'music_id' 不能为空" assert _balance() == 3 assert _open_rows() == []