/ tests / test_statistics_users.py
test_statistics_users.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  test_username = f"statuser_{_suffix}"
12  test_password = "stat_test_pass"
13  
14  
15  @pytest.fixture(scope="module")
16  def client():
17      with TestClient(app) as c:
18          yield c
19  
20  
21  def test_setup(client):
22      """Create a non-admin user for permission tests."""
23      resp = client.post(
24          "/users",
25          json={"username": test_username, "password": test_password, "admin": False, "private": False},
26          auth=ADMIN,
27      )
28      assert resp.status_code in (200, 201)
29  
30  
31  def test_statistics_users_list(client):
32      """GET /statistics/users as admin returns a users list."""
33      resp = client.get("/statistics/users", auth=ADMIN)
34      assert resp.status_code == 200
35      data = resp.json()
36      assert "users" in data
37      assert isinstance(data["users"], list)
38  
39  
40  def test_statistics_users_detail(client):
41      """GET /statistics/users/1 as admin returns user activity details."""
42      resp = client.get("/statistics/users/1", auth=ADMIN)
43      assert resp.status_code == 200
44      data = resp.json()
45      assert "summary" in data
46      assert "daily" in data
47      assert "top_projects" in data
48      assert "hourly" in data
49  
50  
51  def test_statistics_users_non_admin(client):
52      """GET /statistics/users as non-admin should return 403."""
53      resp = client.get("/statistics/users", auth=(test_username, test_password))
54      assert resp.status_code == 403
55  
56  
57  def test_cleanup(client):
58      client.delete(f"/users/{test_username}", auth=ADMIN)