Files
ipam_control/tests/test_users.py
T

70 lines
4.4 KiB
Python
Raw Normal View History

"""Управление пользователями: один сквозной сценарий (создание → права → отключение → пароли → удаление)."""
import uuid
import httpx
from tests.conftest import BASE
def _client(username: str, password: str):
"""Клиент с токеном пользователя; None — вход не удался."""
c = httpx.Client(base_url=BASE, timeout=30)
r = c.post("/auth/login", json={"username": username, "password": password})
if r.status_code != 200:
c.close()
return None
c.headers["Authorization"] = "Bearer " + r.json()["access_token"]
return c
def test_users_management(client):
name, uid, other = f"qa-{uuid.uuid4().hex[:8]}", None, None
try:
created = client.post("/users", json={"username": name, "password": "start-pass-123", "role": "viewer"})
assert created.status_code == 201, created.text
uid = created.json()["id"]
assert created.json()["role"] == "viewer" and created.json()["is_active"] is True
assert client.post("/users", json={"username": name.upper(), "password": "start-pass-123"}).status_code == 409 # логин занят без учёта регистра
assert client.post("/users", json={"username": "system", "password": "start-pass-123"}).status_code == 422 # служебный логин журнала
assert client.post("/users", json={"username": "ab", "password": "start-pass-123"}).status_code == 422 # короткий логин
assert client.post("/users", json={"username": "short-pw", "password": "123"}).status_code == 422 # короткий пароль
other = _client(name, "start-pass-123")
assert other is not None
assert other.get("/auth/me").json()["role"] == "viewer"
assert other.get("/users").status_code == 403 # список пользователей только для админа
assert other.post("/organizations", json={"name": "qa", "inn": "1234567890"}).status_code == 403 # роль «просмотр» — только чтение
# отключение действует немедленно, включая ранее выданный токен
assert client.patch(f"/users/{uid}", json={"is_active": False}).json()["is_active"] is False
assert other.get("/auth/me").status_code == 401
assert _client(name, "start-pass-123") is None
# возврат доступа и сброс пароля администратором
client.patch(f"/users/{uid}", json={"is_active": True, "password": "reset-pass-123"})
assert _client(name, "start-pass-123") is None
other = _client(name, "reset-pass-123")
assert other is not None
# смена своего пароля: нужен текущий, новый не должен совпадать с ним
assert other.post("/users/me/password", json={"current_password": "wrong", "new_password": "third-pass-123"}).status_code == 403
assert other.post("/users/me/password", json={"current_password": "reset-pass-123", "new_password": "reset-pass-123"}).status_code == 422
assert other.post("/users/me/password", json={"current_password": "reset-pass-123", "new_password": "third-pass-123"}).status_code == 200
assert _client(name, "third-pass-123") is not None
assert other.get("/auth/me").status_code == 200 # выданный ранее токен продолжает работать
# свою учётную запись удалить или отключить нельзя
me = client.get("/auth/me").json()
assert client.delete(f"/users/{me['id']}").status_code == 409
assert client.patch(f"/users/{me['id']}", json={"is_active": False}).status_code == 409
assert client.patch(f"/users/{uid}", json={"role": "admin"}).json()["role"] == "admin"
assert client.delete(f"/users/{uid}").status_code == 204
uid = None
assert client.get("/audit", params={"event_type": "user.created"}).json()["total"] >= 1
assert client.get("/audit", params={"event_type": "user.password_reset"}).json()["total"] >= 1
finally:
if other is not None:
other.close()
if uid is not None:
client.delete(f"/users/{uid}")