Archived
上一次重构(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,未被写入。
87 lines
2.3 KiB
Python
87 lines
2.3 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""兼容垫片与同步桥测试。"""
|
|
import asyncio
|
|
|
|
import pytest
|
|
from aiohttp import web
|
|
|
|
from core import aiohttp_compat as req
|
|
from core import async_bridge
|
|
|
|
|
|
@pytest.fixture()
|
|
async def server():
|
|
app = web.Application()
|
|
|
|
async def ok(request):
|
|
return web.json_response({'code': 200, 'data': 'hi'})
|
|
|
|
async def notfound(request):
|
|
return web.json_response({'code': 404}, status=404)
|
|
|
|
async def echo_post(request):
|
|
body = await request.text()
|
|
return web.json_response({'got': body, 'ua': request.headers.get('User-Agent')})
|
|
|
|
app.router.add_get('/ok', ok)
|
|
app.router.add_get('/nf', notfound)
|
|
app.router.add_post('/echo', echo_post)
|
|
|
|
runner = web.AppRunner(app)
|
|
await runner.setup()
|
|
site = web.TCPSite(runner, '127.0.0.1', 0)
|
|
await site.start()
|
|
port = runner.addresses[0][1]
|
|
try:
|
|
yield f'http://127.0.0.1:{port}'
|
|
finally:
|
|
await runner.cleanup()
|
|
|
|
|
|
async def test_get_json(server):
|
|
r = await req.get(server + '/ok')
|
|
assert r.status_code == 200
|
|
assert r.json() == {'code': 200, 'data': 'hi'}
|
|
assert 'code' in r.text
|
|
r.raise_for_status() # 200 不抛
|
|
|
|
|
|
async def test_4xx_does_not_raise_until_raise_for_status(server):
|
|
r = await req.get(server + '/nf')
|
|
assert r.status_code == 404 # 请求本身不抛(同 requests)
|
|
assert r.json() == {'code': 404}
|
|
with pytest.raises(req.HTTPError):
|
|
r.raise_for_status()
|
|
|
|
|
|
async def test_post_headers_forwarded(server):
|
|
r = await req.post(server + '/echo', data={'params': 'x'}, headers={'User-Agent': 'ua-test'})
|
|
body = r.json()
|
|
assert body['ua'] == 'ua-test'
|
|
assert 'params' in body['got']
|
|
|
|
|
|
async def test_network_error_raises_request_exception():
|
|
with pytest.raises(req.RequestException):
|
|
await req.get('http://127.0.0.1:1/nope', timeout=1)
|
|
|
|
|
|
def test_bridge_runs_coro_from_sync():
|
|
async def coro():
|
|
await asyncio.sleep(0.01)
|
|
return 42
|
|
|
|
assert async_bridge.run_sync(coro()) == 42
|
|
|
|
|
|
async def test_bridge_rejects_inside_loop():
|
|
async def coro():
|
|
return 1
|
|
|
|
c = coro()
|
|
try:
|
|
with pytest.raises(RuntimeError):
|
|
async_bridge.run_sync(c)
|
|
finally:
|
|
c.close() # run_sync 拒绝执行,需自行关闭以免「未 await」告警
|