Files
group_xinghuo_jinrong/tests/test_api.py
T
zyi b19a2415f9 feat: 数据分析 Agent 实现(API/服务/表结构元数据/文档/测试)
- 新增 app/api、app/service 数据分析 Agent 全套服务与接口
- schemas.py 重构为 schemas 包(analyst schema)
- 新增 SQL 防注入、guardrail、缓存、字典、LLM 等服务
- 新增 tests 测试套件与 scripts/dev、scripts/setup 脚本
- 补充需求规格、架构说明书、开发清单、表设计等文档
2026-09-09 18:04:45 +08:00

82 lines
2.4 KiB
Python

"""API 层测试(FastAPI TestClient)。"""
import unittest
from fastapi.testclient import TestClient
from app.main import app
from app.utils.auth import create_dev_token
client = TestClient(app)
def analyst_token():
return create_dev_token("STAFF-API", ["analyst"], "analyst")
def advisor_token():
return create_dev_token("STAFF-ADV", ["advisor"], "advisor")
class TestApi(unittest.TestCase):
def test_health(self):
r = client.get("/health")
self.assertEqual(r.status_code, 200)
def test_chat_no_token(self):
r = client.post("/api/analyst/chat", json={"question": "客户总数"})
self.assertEqual(r.status_code, 401)
def test_chat_bad_token(self):
r = client.post(
"/api/analyst/chat",
json={"question": "客户总数"},
headers={"Authorization": "Bearer bad"},
)
self.assertEqual(r.status_code, 401)
def test_chat_success(self):
r = client.post(
"/api/analyst/chat",
json={"question": "客户总数是多少"},
headers={"Authorization": f"Bearer {analyst_token()}"},
)
self.assertEqual(r.status_code, 200)
data = r.json()
self.assertIn(data["status"], ("success", "degrade"))
self.assertIn("answer", data)
self.assertIn("table", data)
def test_dashboard(self):
r = client.get(
"/api/analyst/dashboard",
headers={"Authorization": f"Bearer {analyst_token()}"},
)
self.assertEqual(r.status_code, 200)
self.assertIn("cards", r.json())
def test_assets_advisor_forbidden(self):
r = client.post(
"/api/analyst/assets",
json={"kind": "dict", "payload": {"metric_key": "x"}},
headers={"Authorization": f"Bearer {advisor_token()}"},
)
self.assertEqual(r.status_code, 403)
def test_assets_analyst_ok(self):
import uuid
key = f"test_k_{uuid.uuid4().hex[:8]}"
r = client.post(
"/api/analyst/assets",
json={
"kind": "dict",
"payload": {"metric_key": key, "metric_name": "测试指标", "definition": "测试口径"},
},
headers={"Authorization": f"Bearer {analyst_token()}"},
)
self.assertEqual(r.status_code, 200)
self.assertTrue(r.json()["ok"])
if __name__ == "__main__":
unittest.main()