This repository has been archived on 2026-10-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
snowy-yang 838d635bc5 fix: 修复重构遗留缺陷,补齐 pyright 检查盲区
上一次重构(8446166)声称「pyright 0 错误」,但 pyproject 里 pyright 的 include
只覆盖 core/web/services —— 根目录 6 个应用模块与整个 tests/ 从未被检查,而
requests→sync_http 迁移的遗留恰好全部藏在那里。补齐 include 后立刻暴露
7 errors + 9 warnings,其中数处在运行时静默失效。

修复:
- services/runtime.py:删除 _podcast_billing_count/_billing_ids_count 两个
  无调用方的死函数。它们仍调用 api_service._safe_get_request_data(),而该方法
  在剥离 Flask 时已被删除,异常又被 except 吞掉 —— 一旦被调用,播客/歌单计费
  恒为 1 次且不报任何错。路由层已各自实现同口径版本,故整体删除。
- web/routers/admin_site.py:备份上传的类型判定必须用 starlette 的 UploadFile。
  fastapi.UploadFile 是它的子类,而 request.form() 返回基类实例,用错会让
  isinstance 恒为 False,把每一次真实上传都判成「请选择数据库文件」。
  已补 4 例真实 multipart 回归测试,并用变异测试确认能抓住该缺陷。
- auth_system.py:修正 create_user(实返 sqlite3.Row|None)与 list_cards
  (实返 (cards,total) 元组)与实现不符的返回注解;注解一改正,立刻暴露出被它
  掩盖的 register.py 中 int(user['id']) 未做 None 检查的 500 崩溃路径,已补守卫。
- music_downloader.py:修正注解引用的 core.sync_http.Response(正确名应为
  SyncResponse);封面缓存淘汰不再读类型为 Optional 的 deque.maxlen,改用命名常量。
- services/runtime.py:zip worker 的 result.music_info 可能为 None,原样使用会
  炸掉整批任务,改为按单曲失败处理。
- music_api.py:三处 isinstance 三元表达式收敛为 _as_dict() 帮助函数。
- web/main.py:文档串移除已删除的 Flask 兜底描述,补充 data/ 相对 CWD 解析的提醒。

验证:ruff check 通过;pyright 0 errors / 0 warnings(filesAnalyzed=67);
pytest 144 passed;真实 uvicorn 启动冒烟通过(/health、/、静态资源 200,
未鉴权管理端点 403)。生产库仅做只读 integrity_check,未被写入。
2026-09-26 11:52:06 +08:00

91 lines
2.8 KiB
Python

# -*- coding: utf-8 -*-
"""音频流代理测试:签名校验、HEAD、Range 透传、无效 token。"""
from typing import Any
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from core import security
from web.routers import stream as stream_router
SECRET = 'stream-test-secret'
PAYLOAD = b'AUDIO-DATA-' * 1000 # 11000 字节
@pytest.fixture()
def client(monkeypatch):
security.init_secret_key(SECRET)
app = FastAPI()
app.include_router(stream_router.router, prefix='/api/v1')
class _Upstream:
def __init__(self):
self.status = 200
self.headers = {'Content-Type': 'audio/mpeg', 'Content-Length': str(len(PAYLOAD)),
'Accept-Ranges': 'bytes'}
self.closed = False
self.content = self
async def iter_chunked(self, n):
for i in range(0, len(PAYLOAD), n):
yield PAYLOAD[i:i + n]
def close(self):
self.closed = True
state: dict[str, Any] = {'last_range': None, 'upstream': None}
async def fake_open(method, url, *, headers=None, timeout=None, **kw):
state['last_range'] = (headers or {}).get('Range')
up = _Upstream()
if state['last_range']:
up.status = 206
up.headers = dict(up.headers)
up.headers['Content-Range'] = f'bytes 0-99/{len(PAYLOAD)}'
state['upstream'] = up
return up
monkeypatch.setattr('web.routers.stream.http_client.open', fake_open)
return TestClient(app), state
def test_invalid_token(client):
c, _ = client
r = c.get('/api/v1/audio_stream?token=bogus')
assert r.status_code == 403
def test_head_no_upstream(client):
c, state = client
r = c.head('/api/v1/audio_stream?token=x')
assert r.status_code == 200
assert r.headers['accept-ranges'] == 'bytes'
assert state['upstream'] is None # HEAD 不应请求上游
def test_stream_full(client):
c, _ = client
token = security.make_audio_token('http://m801.music.126.net/a.mp3')
r = c.get(f'/api/v1/audio_stream?token={token}')
assert r.status_code == 200
assert r.content == PAYLOAD
assert r.headers['cache-control'] == 'no-store'
assert r.headers['content-length'] == str(len(PAYLOAD))
def test_range_forwarded_and_206(client):
c, state = client
token = security.make_audio_token('http://m801.music.126.net/a.mp3')
r = c.get(f'/api/v1/audio_stream?token={token}', headers={'Range': 'bytes=0-99'})
assert state['last_range'] == 'bytes=0-99' # Range 已透传上游
assert r.status_code == 206
assert 'content-range' in r.headers
def test_upstream_closed_on_complete(client):
c, state = client
token = security.make_audio_token('http://m801.music.126.net/a.mp3')
c.get(f'/api/v1/audio_stream?token={token}')
assert state['upstream'].closed is True