Files
group_xinghuo_jinrong/tests/test_api.py
T

82 lines
2.4 KiB
Python
Raw Normal View History

"""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()