Files
AIPortPilot/backend/tests/test_risks.py
T
selfrelease 94be6189e9 feat: T1.5 风险工作台 — 后端 CRUD + 前端风险列表
- 后端:risks 路由(列表/详情/创建/更新/删除)+ 状态流转
- 前端:风险工作台页(卡片列表、状态筛选、内联状态切换、删除)
- 测试:6 个风险 CRUD 测试(总计 43 tests passed)
- 前端构建 13 路由成功
2026-07-18 22:06:30 +08:00

173 lines
5.3 KiB
Python

"""风险事件 CRUD 测试。"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from app.core.database import Base, get_db
from app.main import app
TEST_DATABASE_URL = "sqlite+aiosqlite:///file::memory:?cache=shared&uri=true"
test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
test_session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
async def override_get_db():
async with test_session_factory() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
app.dependency_overrides[get_db] = override_get_db
@pytest.fixture(scope="module", autouse=True)
async def setup_db():
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
def auth_headers(client: TestClient):
"""注册并登录。"""
client.post(
"/api/v1/auth/register",
json={
"email": "risk_test@example.com",
"password": "password123",
"name": "测试投资经理",
"tenant_name": "测试机构",
"role": "investor",
},
)
resp = client.post(
"/api/v1/auth/login",
json={"email": "risk_test@example.com", "password": "password123"},
)
token = resp.json()["data"]["access_token"]
return {"Authorization": f"Bearer {token}"}
@pytest.fixture
def company_id(client: TestClient, auth_headers: dict):
"""创建测试企业。"""
resp = client.post(
"/api/v1/companies",
json={"name": "风险测试公司", "industry": "AI"},
headers=auth_headers,
)
return resp.json()["data"]["id"]
class TestCreateRisk:
"""创建风险事件。"""
def test_create_success(self, client: TestClient, auth_headers: dict, company_id: str):
response = client.post(
"/api/v1/risks",
json={
"company_id": company_id,
"type": "financial",
"severity": "high",
"title": "现金流预警",
"description": "月度烧钱率超过预期",
"suggested_action": "建议与创始人沟通融资计划",
},
headers=auth_headers,
)
assert response.status_code == 201
data = response.json()
assert data["code"] == 0
assert data["data"]["title"] == "现金流预警"
assert data["data"]["status"] == "open"
assert data["data"]["severity"] == "high"
def test_create_without_auth(self, client: TestClient):
response = client.post(
"/api/v1/risks",
json={"company_id": "x", "type": "financial", "title": "测试"},
)
assert response.status_code == 401
class TestListRisks:
"""风险列表。"""
def test_list_success(self, client: TestClient, auth_headers: dict, company_id: str):
# 先创建一条
client.post(
"/api/v1/risks",
json={"company_id": company_id, "type": "operational", "title": "人员流失"},
headers=auth_headers,
)
response = client.get("/api/v1/risks", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["data"]["total"] >= 1
def test_list_by_status(self, client: TestClient, auth_headers: dict, company_id: str):
response = client.get(
"/api/v1/risks?status=open",
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert all(item["status"] == "open" for item in data["data"]["items"])
class TestUpdateRisk:
"""更新风险事件。"""
def test_update_status(self, client: TestClient, auth_headers: dict, company_id: str):
create_resp = client.post(
"/api/v1/risks",
json={"company_id": company_id, "type": "ai_specific", "title": "AI 依赖风险"},
headers=auth_headers,
)
risk_id = create_resp.json()["data"]["id"]
response = client.put(
f"/api/v1/risks/{risk_id}",
json={"status": "in_progress", "assigned_to": "someone"},
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["data"]["status"] == "in_progress"
class TestDeleteRisk:
"""删除风险事件。"""
def test_delete_success(self, client: TestClient, auth_headers: dict, company_id: str):
create_resp = client.post(
"/api/v1/risks",
json={"company_id": company_id, "type": "org", "title": "组织架构风险"},
headers=auth_headers,
)
risk_id = create_resp.json()["data"]["id"]
response = client.delete(
f"/api/v1/risks/{risk_id}",
headers=auth_headers,
)
assert response.status_code == 200
get_resp = client.get(
f"/api/v1/risks/{risk_id}",
headers=auth_headers,
)
assert get_resp.status_code == 404