test_project_guards_endpoints.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 ADMIN = ("admin", RESTAI_DEFAULT_PASSWORD) 9 10 _suffix = str(random.randint(0, 999999)) 11 team_name = f"guards_team_{_suffix}" 12 llm_name = f"guards_llm_{_suffix}" 13 proj_name = f"guards_proj_{_suffix}" 14 team_id = None 15 project_id = None 16 17 18 @pytest.fixture(scope="module") 19 def client(): 20 with TestClient(app) as c: 21 yield c 22 23 24 def test_setup(client): 25 """Create team, LLM, and a block project for guard endpoint tests.""" 26 global team_id, project_id 27 # Create LLM 28 client.post( 29 "/llms", 30 json={ 31 "name": llm_name, 32 "class_name": "OpenAI", 33 "options": {"model": "gpt-test", "api_key": "sk-fake"}, 34 "privacy": "public", 35 }, 36 auth=ADMIN, 37 ) 38 39 # Create team with LLM 40 resp = client.post( 41 "/teams", 42 json={"name": team_name, "users": [], "admins": [], "llms": [llm_name]}, 43 auth=ADMIN, 44 ) 45 assert resp.status_code in (200, 201) 46 team_id = resp.json()["id"] 47 48 # Create a block project (no LLM required) 49 resp = client.post( 50 "/projects", 51 json={"name": proj_name, "type": "block", "team_id": team_id}, 52 auth=ADMIN, 53 ) 54 assert resp.status_code == 201 55 project_id = resp.json()["project"] 56 57 58 def test_guards_summary(client): 59 """GET /projects/{id}/guards/summary returns guard statistics.""" 60 resp = client.get( 61 f"/projects/{project_id}/guards/summary", 62 auth=ADMIN, 63 ) 64 assert resp.status_code == 200 65 data = resp.json() 66 assert "total_checks" in data 67 assert "total_blocks" in data 68 assert "block_rate" in data 69 70 71 def test_guards_events(client): 72 """GET /projects/{id}/guards/events returns paginated event list.""" 73 resp = client.get( 74 f"/projects/{project_id}/guards/events", 75 auth=ADMIN, 76 ) 77 assert resp.status_code == 200 78 data = resp.json() 79 assert "events" in data 80 assert isinstance(data["events"], list) 81 assert "total" in data 82 83 84 def test_guards_daily(client): 85 """GET /projects/{id}/guards/daily returns daily guard counts.""" 86 resp = client.get( 87 f"/projects/{project_id}/guards/daily", 88 auth=ADMIN, 89 ) 90 assert resp.status_code == 200 91 data = resp.json() 92 assert "events" in data 93 assert isinstance(data["events"], list) 94 95 96 def test_cleanup(client): 97 client.delete(f"/projects/{project_id}", auth=ADMIN) 98 client.delete(f"/llms/{llm_name}", auth=ADMIN) 99 client.delete(f"/teams/{team_id}", auth=ADMIN)