test_statistics.py
1 import pytest 2 from fastapi.testclient import TestClient 3 4 from restai.config import RESTAI_DEFAULT_PASSWORD 5 from restai.main import app 6 7 8 @pytest.fixture(scope="module") 9 def client(): 10 with TestClient(app) as c: 11 yield c 12 13 14 def test_top_projects(client): 15 response = client.get( 16 "/statistics/top-projects", 17 auth=("admin", RESTAI_DEFAULT_PASSWORD), 18 ) 19 assert response.status_code == 200 20 data = response.json() 21 assert "projects" in data 22 assert isinstance(data["projects"], list) 23 24 25 def test_top_projects_with_limit(client): 26 response = client.get( 27 "/statistics/top-projects?limit=5", 28 auth=("admin", RESTAI_DEFAULT_PASSWORD), 29 ) 30 assert response.status_code == 200 31 data = response.json() 32 assert "projects" in data 33 assert len(data["projects"]) <= 5 34 35 36 def test_summary(client): 37 """GET /statistics/summary returns expected fields.""" 38 resp = client.get("/statistics/summary", auth=("admin", RESTAI_DEFAULT_PASSWORD)) 39 assert resp.status_code == 200 40 data = resp.json() 41 for key in ("total_projects", "total_users", "total_teams", "total_tokens", "total_cost"): 42 assert key in data 43 44 45 def test_daily_tokens(client): 46 """GET /statistics/daily-tokens returns token data.""" 47 resp = client.get("/statistics/daily-tokens?days=7", auth=("admin", RESTAI_DEFAULT_PASSWORD)) 48 assert resp.status_code == 200 49 data = resp.json() 50 assert "tokens" in data 51 assert isinstance(data["tokens"], list) 52 53 54 def test_top_llms(client): 55 """GET /statistics/top-llms returns LLM usage data.""" 56 resp = client.get("/statistics/top-llms?limit=5", auth=("admin", RESTAI_DEFAULT_PASSWORD)) 57 assert resp.status_code == 200 58 data = resp.json() 59 assert "llms" in data 60 assert isinstance(data["llms"], list) 61 62 63 def test_statistics_non_admin(client): 64 """Non-admin user can access statistics (for their own projects).""" 65 import random 66 username = f"stats_user_{random.randint(0, 1000000)}" 67 auth = ("admin", RESTAI_DEFAULT_PASSWORD) 68 client.post("/users", json={"username": username, "password": "pass123", "admin": False, "private": False}, auth=auth) 69 70 resp = client.get("/statistics/summary", auth=(username, "pass123")) 71 assert resp.status_code == 200 72 73 resp = client.get("/statistics/top-projects", auth=(username, "pass123")) 74 assert resp.status_code == 200 75 76 client.delete(f"/users/{username}", auth=auth)