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
NeteaseUrl/tests/test_aiohttp_compat.py
T
snowy-yang c77ef40fd5 feat(db): 同步栈读写并发(_q 去锁)+ core.db 并发/跨loop 修复
auth_system._q:单语句读不再持 _DB_LOCK —— WAL 下每连接读一致性快照,
读写互不阻塞;旧实现把全部读也串行化且被写挡住。写事务(_x 与 24 个
with _DB_LOCK 块,经扫描均为写事务)仍全程串行,无写-写竞争。

core.db 并发修复(由测试暴露的真实缺陷):
- WAL 切换竞态:并发连接同时执行 PRAGMA journal_mode=WAL 争排他锁
  → 专用锁内串行切换 + 二次复查(busy_timeout 前置)
- 跨事件循环锁:模块级 asyncio.Lock 绑定首个 loop,多 loop 场景报
  "bound to a different event loop" → 锁按 loop 隔离

测试:25/25 通过(新增「读不被写锁阻塞」红转绿、读+同步写者并发 WAL、
异步并发读);
lint: ruff All checks passed;pyright 0 errors。
验收:冒烟 10/10、奇偶校验 2/2、uvicorn 真实启动 Flask 兜底+FastAPI 双通。
2026-09-26 01:03:18 +08:00

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 = site._server.sockets[0].getsockname()[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」告警