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 4962542e78 feat(core): requests 兼容异步垫片 + 同步/异步桥
- core/aiohttp_compat.py:以 requests 同形 API(post/get + Response.json/text/
  status_code/raise_for_status + HTTPError/RequestException/Timeout)实现异步请求,
  使既有 requests 风格代码可「加 await + async def」最小改动迁移;4xx/5xx 不抛、
  仅 raise_for_status() 抛(与 requests 语义一致,保住风控判断逻辑)
- core/async_bridge.py:run_sync(coro) 经常驻后台事件循环线程执行协程并阻塞等待,
  供迁移期同步调用方(遗留 Flask 路由/线程池)复用异步实现

验证:pytest 16/16;ruff All checks passed;pyright 0 errors。
2026-09-26 00:27:47 +08:00

83 lines
2.2 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
with pytest.raises(RuntimeError):
async_bridge.run_sync(coro())