fix: Host中间件审查修复(本地开发文档/顺序守护测试/ws断连分支/夹具清理)

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
浅念
2026-10-12 20:47:01 +08:00
parent eaa5bf7e51
commit fd0f49870c
4 changed files with 32 additions and 7 deletions
+4 -3
View File
@@ -10,6 +10,7 @@ import pytest
from fastapi.testclient import TestClient
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.pool import NullPool
from urllib.parse import urlsplit
from app.engine.models import Base
@@ -152,7 +153,7 @@ def app_test_client(app_instance, base_url, cleanup_root):
try:
with TenantTestClient(
app_instance, base_url=base_url,
ws_default_host=base_url.removeprefix("http://")) as c:
ws_default_host=urlsplit(base_url).netloc) as c:
yield c
finally:
app_instance.state.registry = None
@@ -171,8 +172,8 @@ def app_client(tmp_path):
TestClient——同一 app 上两个 client 各跑一次 lifespan 会共享
registry 而 engine 各绑一个循环,跨循环死锁。
"""
build_app(SEED_DIR, tmp_path)
with app_test_client(app, f"http://{JIANCAI_HOST}", tmp_path) as c:
a = build_app(SEED_DIR, tmp_path)
with app_test_client(a, f"http://{JIANCAI_HOST}", tmp_path) as c:
yield c
+13 -1
View File
@@ -11,6 +11,8 @@ import shutil
import pytest
from starlette.websockets import WebSocketDisconnect
from app.main import app
from app.platform.host_middleware import TenantHostMiddleware
from tests.conftest import (
AUTO_HOST,
JIANCAI_HOST,
@@ -22,10 +24,20 @@ from tests.conftest import (
NOPE_HOST = "nope.example.com"
# ---- 中间件挂载顺序守护 -------------------------------------------------------
def test_tenant_middleware_is_outermost_user_middleware():
# add_middleware 后加者居 user_middleware[0] = 最外层。租户解析必须
# 先于一切用户中间件(里层中间件/路由才读得到 state.tenant)——未来
# 新中间件若更晚 add_middleware 插到租户中间件外层,此测试即红。
assert app.user_middleware[0].cls is TenantHostMiddleware
# ---- 平台级豁免 -------------------------------------------------------------
def test_known_host_serves_health(app_client):
def test_health_served_for_any_host(app_client):
# /health 在任何 Host 下可达(部署健康检查 curl 127.0.0.1:8018,
# Host 是 IP:端口,对 registry 必然未知)
assert app_client.get("/health").status_code == 200