phase-8: polish, global search, audit log, packaging, and demo docs
This commit is contained in:
@@ -8,6 +8,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
from app.core.db import get_db
|
||||
from app.main import app
|
||||
from app.models import Base
|
||||
from app.routers.auth import reset_login_rate_limiter
|
||||
|
||||
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
|
||||
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
|
||||
@@ -111,3 +112,10 @@ def client(db):
|
||||
finally:
|
||||
c.close()
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_login_rate_limiter():
|
||||
reset_login_rate_limiter()
|
||||
yield
|
||||
reset_login_rate_limiter()
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, AuditLog, Base, Department, User
|
||||
from app.routers.auth import MAX_LOGIN_ATTEMPTS, reset_login_rate_limiter
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_phase8_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("phase8_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_global_search_grouped_and_department_scoped(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||
icu_dept = db.query(Department).filter(Department.id == dept_user.department_id).first()
|
||||
assert dept_user is not None and icu_dept is not None
|
||||
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu_dept.id).first()
|
||||
non_icu_asset = db.query(Asset).filter(Asset.department_id != icu_dept.id).first()
|
||||
assert icu_asset is not None and non_icu_asset is not None
|
||||
|
||||
# Broad search returns grouped assets & complaints capped at 8 each
|
||||
broad = client.get("/api/search?q=PHRC", headers=bio_headers)
|
||||
assert broad.status_code == 200, broad.text
|
||||
data = broad.json()
|
||||
assert isinstance(data["assets"], list) and 0 < len(data["assets"]) <= 8
|
||||
assert isinstance(data["complaints"], list) and len(data["complaints"]) <= 8
|
||||
assert {"id", "asset_code", "name", "serial_no", "department_name", "status"}.issubset(
|
||||
data["assets"][0].keys()
|
||||
)
|
||||
|
||||
# Complaint search by prefix
|
||||
cmp_search = client.get("/api/search?q=CMP", headers=bio_headers)
|
||||
assert cmp_search.status_code == 200
|
||||
assert len(cmp_search.json()["complaints"]) > 0
|
||||
assert {
|
||||
"id",
|
||||
"complaint_no",
|
||||
"asset_code",
|
||||
"asset_name",
|
||||
"department_name",
|
||||
"call_status",
|
||||
"priority",
|
||||
}.issubset(cmp_search.json()["complaints"][0].keys())
|
||||
|
||||
# Department user sees ICU asset, cannot see non-ICU asset
|
||||
icu_res = client.get(f"/api/search?q={icu_asset.asset_code}", headers=dept_headers)
|
||||
assert icu_res.status_code == 200
|
||||
assert any(a["asset_code"] == icu_asset.asset_code for a in icu_res.json()["assets"])
|
||||
|
||||
other_res = client.get(f"/api/search?q={non_icu_asset.asset_code}", headers=dept_headers)
|
||||
assert other_res.status_code == 200
|
||||
assert other_res.json()["assets"] == []
|
||||
assert other_res.json()["complaints"] == []
|
||||
|
||||
# Empty query rejected
|
||||
assert client.get("/api/search?q=", headers=bio_headers).status_code == 422
|
||||
|
||||
|
||||
def test_audit_logs_rbac_and_filters(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
for email in ("bio@poona.demo", "mgmt@poona.demo", "dept@poona.demo", "coord@poona.demo"):
|
||||
headers = _auth_headers(client, email)
|
||||
assert client.get("/api/audit-logs", headers=headers).status_code == 403
|
||||
|
||||
# Ensure there is at least one distinct AuditLog entry via API/DB
|
||||
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||
assert admin_user is not None
|
||||
log_entry = AuditLog(
|
||||
entity_type="asset",
|
||||
entity_id=9999,
|
||||
action="phase8_audit_probe",
|
||||
changes_json='{"status": {"old": "in_service", "new": "under_repair"}}',
|
||||
by_user_id=admin_user.id,
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
|
||||
res = client.get("/api/audit-logs?entity_type=asset&action=phase8_audit_probe", headers=admin_headers)
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert body["total"] >= 1
|
||||
assert len(body["items"]) >= 1
|
||||
first = body["items"][0]
|
||||
assert first["entity_type"] == "asset"
|
||||
assert first["action"] == "phase8_audit_probe"
|
||||
assert first["by_user_id"] == admin_user.id
|
||||
assert first["by_user_name"] == admin_user.name
|
||||
assert "under_repair" in first["changes_json"]
|
||||
|
||||
# Search filter `q`
|
||||
q_res = client.get("/api/audit-logs?q=phase8_audit_probe", headers=admin_headers)
|
||||
assert q_res.status_code == 200
|
||||
assert q_res.json()["total"] == 1
|
||||
|
||||
|
||||
def test_login_rate_limiter_429_and_reset(client):
|
||||
reset_login_rate_limiter()
|
||||
for i in range(MAX_LOGIN_ATTEMPTS):
|
||||
res = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
|
||||
)
|
||||
assert res.status_code == 401, f"Attempt {i + 1} unexpected status {res.status_code}"
|
||||
|
||||
# Attempt 16 triggers 429 RATE_LIMITED
|
||||
blocked = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.json()["code"] == "RATE_LIMITED"
|
||||
|
||||
# Reset restores login capability
|
||||
reset_login_rate_limiter()
|
||||
ok = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "admin@poona.demo", "password": "Demo@123"},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
|
||||
|
||||
def test_database_indexes_defined():
|
||||
expected_indexed_columns = {
|
||||
"assets": {"asset_code", "serial_no", "department_id", "category_id", "location_id", "status"},
|
||||
"complaints": {"complaint_no", "asset_id", "registered_at", "call_status", "assigned_to_id"},
|
||||
"contracts": {"asset_id", "start_date", "end_date"},
|
||||
"warranties": {"asset_id", "start_date", "end_date"},
|
||||
"insurance_policies": {"asset_id", "start_date", "end_date"},
|
||||
"calibration_records": {"asset_id", "plan_id", "due_date"},
|
||||
"pm_records": {"asset_id", "schedule_id", "planned_date"},
|
||||
"demo_equipment": {"department_id", "expected_return_date"},
|
||||
"department_visits": {"department_id", "visit_date"},
|
||||
"attachments": {"entity_type", "entity_id"},
|
||||
"notifications": {"created_at", "type"},
|
||||
"audit_logs": {"entity_type", "entity_id", "by_user_id", "at"},
|
||||
}
|
||||
for table_name, cols in expected_indexed_columns.items():
|
||||
table = Base.metadata.tables[table_name]
|
||||
indexed = {col.name for idx in table.indexes for col in idx.columns}
|
||||
missing = cols - indexed
|
||||
assert not missing, f"Missing indexes on {table_name}: {missing}"
|
||||
Reference in New Issue
Block a user