Files
celtic-life-science/tests/e2e/test_user_role_change.py
Shubhankar45 4e5e95775d --
2026-10-27 12:03:31 +00:00

77 lines
3.1 KiB
Python

"""An Administrator can change another user's role; the old role's assignments end."""
import uuid
from sqlalchemy import select
from app.doctors.models import DoctorAssignment
from tests.conftest import DEFAULT_PASSWORD
API = "/api/v1"
async def _patch(client, auth, user, body, as_="admin"):
return await client.patch(f"{API}/users/{user.id}", headers=auth[as_], json=body)
class TestAdminChangesRole:
async def test_mr_becomes_am_and_loses_hq_and_doctors(self, client, auth, org, db):
doctor = await client.post(
f"{API}/doctors",
headers=auth["mr1"],
json={"headquarters_id": str(org["hq1"].id), "name": "Dr A", "clinic_address": "Puri"},
)
assert doctor.status_code == 201
resp = await _patch(client, auth, org["mr1"], {"role": "AM"})
assert resp.status_code == 200, resp.text
assert resp.json()["role"] == "AM"
assert resp.json()["headquarters_id"] is None
# The doctor stays in the headquarters but is no longer assigned to anyone.
active = await db.execute(
select(DoctorAssignment).where(
DoctorAssignment.doctor_id == uuid.UUID(doctor.json()["id"]),
DoctorAssignment.effective_to.is_(None),
)
)
assert active.scalars().first() is None
async def test_am_becomes_mr_and_releases_headquarters(self, client, auth, org):
resp = await _patch(
client, auth, org["am1"], {"role": "MR", "headquarters_id": str(org["hq2"].id)}
)
assert resp.status_code == 200, resp.text
assert resp.json()["headquarters_id"] == str(org["hq2"].id)
mappings = await client.get(f"{API}/headquarters/area-managers", headers=auth["admin"])
assert str(org["am1"].id) not in {m["area_manager_user_id"] for m in mappings.json()}
async def test_gm_becomes_am(self, client, auth, org):
resp = await _patch(client, auth, org["gm"], {"role": "AM"})
assert resp.status_code == 200, resp.text
assert resp.json()["role"] == "AM"
async def test_role_change_signs_the_user_out(self, client, auth, org):
login = await client.post(
f"{API}/auth/login",
json={"email": org["gm"].email, "password": DEFAULT_PASSWORD},
)
await _patch(client, auth, org["gm"], {"role": "AM"})
again = await client.post(
f"{API}/auth/refresh", json={"refresh_token": login.json()["refresh_token"]}
)
assert again.status_code == 401
async def test_becoming_mr_needs_a_headquarters(self, client, auth, org):
resp = await _patch(client, auth, org["gm"], {"role": "MR"})
assert resp.status_code == 422
async def test_admin_cannot_change_own_role(self, client, auth, org):
resp = await _patch(client, auth, org["admin"], {"role": "GM"})
assert resp.status_code == 422
async def test_only_admin_can_change_a_role(self, client, auth, org):
resp = await _patch(client, auth, org["mr1"], {"role": "AM"}, as_="gm")
assert resp.status_code == 403