test_project_analytics.py
1 import random 2 import pytest 3 from fastapi.testclient import TestClient 4 5 from restai.config import RESTAI_DEFAULT_PASSWORD 6 from restai.main import app 7 8 suffix = str(random.randint(0, 10000000)) 9 team_name = f"analytics_team_{suffix}" 10 llm_name = f"analytics_llm_{suffix}" 11 project_name = f"analytics_proj_{suffix}" 12 13 team_id = None 14 project_id = None 15 16 ADMIN = ("admin", RESTAI_DEFAULT_PASSWORD) 17 18 19 @pytest.fixture(scope="module") 20 def client(): 21 with TestClient(app) as c: 22 yield c 23 24 25 def test_setup(client): 26 """Create team, LLM, and block project for analytics tests.""" 27 global team_id, project_id 28 # Create LLM 29 client.post( 30 "/llms", 31 json={ 32 "name": llm_name, 33 "class_name": "OpenAI", 34 "options": {"model": "gpt-test", "api_key": "sk-fake"}, 35 "privacy": "public", 36 }, 37 auth=ADMIN, 38 ) 39 40 # Create team 41 resp = client.post( 42 "/teams", 43 json={"name": team_name, "users": [], "admins": [], "llms": [llm_name]}, 44 auth=ADMIN, 45 ) 46 assert resp.status_code == 201 47 team_id = resp.json()["id"] 48 49 # Create block project 50 resp = client.post( 51 "/projects", 52 json={"name": project_name, "type": "block", "team_id": team_id}, 53 auth=ADMIN, 54 ) 55 assert resp.status_code == 201 56 project_id = resp.json()["project"] 57 58 59 def test_daily_tokens(client): 60 """GET /projects/{id}/tokens/daily returns 200 with a tokens list.""" 61 resp = client.get(f"/projects/{project_id}/tokens/daily", auth=ADMIN) 62 assert resp.status_code == 200 63 data = resp.json() 64 assert "tokens" in data 65 assert isinstance(data["tokens"], list) 66 67 68 def test_chunking_analytics_non_rag(client): 69 """Chunking analytics returns 400 for a non-RAG (block) project.""" 70 resp = client.get( 71 f"/projects/{project_id}/analytics/chunking", auth=ADMIN 72 ) 73 assert resp.status_code == 400 74 assert "RAG" in resp.json()["detail"] 75 76 77 def test_conversations(client): 78 """GET /projects/{id}/analytics/conversations returns 200.""" 79 resp = client.get( 80 f"/projects/{project_id}/analytics/conversations", auth=ADMIN 81 ) 82 assert resp.status_code == 200 83 data = resp.json() 84 assert "summary" in data 85 assert "total_messages" in data["summary"] 86 assert "total_conversations" in data["summary"] 87 88 89 def test_sources_non_rag(client): 90 """Source analytics returns 400 for a non-RAG (block) project.""" 91 resp = client.get( 92 f"/projects/{project_id}/analytics/sources", auth=ADMIN 93 ) 94 assert resp.status_code == 400 95 assert "RAG" in resp.json()["detail"] 96 97 98 def test_cleanup(client): 99 """Remove all test resources.""" 100 if project_id: 101 client.delete(f"/projects/{project_id}", auth=ADMIN) 102 if team_id: 103 client.delete(f"/teams/{team_id}", auth=ADMIN) 104 client.delete(f"/llms/{llm_name}", auth=ADMIN)