Files
gatekeeper/test/test_services/test_group_manager.py
T
ahtlon 7182a520e2
Pull-Request Vibe Check / ci-test (pull_request) Successful in 31s
Test python action / test (push) Failing after 42s
Check flake syntax / flake-check (push) Successful in 1m57s
Remove nullable from card.group_id
Fix get_future events
2026-11-10 14:57:54 +01:00

226 lines
7.8 KiB
Python

from datetime import UTC, datetime
import pytest
from sqlmodel import select
def test_create_group(client, auth_headers):
"""Test creating a new group."""
group_data = {"name": "New Test Group"}
response = client.post("/api/v1/groups/", json=group_data, headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["name"] == "New Test Group"
assert "id" in data
def test_create_duplicate_group(client, auth_headers, test_group):
"""Test creating a group with a duplicate name."""
group_data = {"name": test_group.name}
response = client.post("/api/v1/groups/", json=group_data, headers=auth_headers)
# This should fail due to unique constraint
assert response.status_code == 409 # Validation error
def test_get_groups(client, auth_headers, test_group):
"""Test retrieving all groups."""
response = client.get("/api/v1/groups/", headers=auth_headers)
assert response.status_code == 200
groups = response.json()
assert len(groups) >= 1
group_names = [group["name"] for group in groups]
assert test_group.name in group_names
def test_delete_group(client, auth_headers, test_group):
"""Test deleting a group."""
response = client.delete(f"/api/v1/groups/{test_group.id}", headers=auth_headers)
assert response.status_code == 200
assert "deleted successfully" in response.json()["message"].lower()
# Verify group is deleted
response = client.get("/api/v1/groups/", headers=auth_headers)
groups = response.json()
assert not any(group["id"] == test_group.id for group in groups)
def _group_with_card(client, auth_headers, db_session, name):
"""Create a group through the API and attach a card to it directly in the
db (POST /api/v1/cards/ needs a physical card to write to)."""
from app.model.models import Card
group = client.post("/api/v1/groups/", json={"name": name}, headers=auth_headers)
assert group.status_code == 200
group_id = group.json()["id"]
db_session.add(
Card(
key=f"key-{name}",
card_serial="00:00:00:00:00:00:00",
name=f"card-{name}",
enabled=True,
group_id=group_id,
last_used=datetime.now(UTC),
)
)
db_session.commit()
return group_id
def test_delete_group_with_assigned_card_is_refused(client, auth_headers, db_session):
"""A group that still has a card assigned must not be deleted."""
from app.model.models import Card, GroupDB
group_id = _group_with_card(client, auth_headers, db_session, "group_with_card")
response = client.delete(f"/api/v1/groups/{group_id}", headers=auth_headers)
assert response.status_code == 409
assert "card" in response.json()["detail"].lower()
db_session.expire_all()
assert db_session.get(GroupDB, group_id) is not None
assert (
len(db_session.exec(select(Card).where(Card.group_id == group_id)).all()) == 1
)
def test_delete_group_refuses_even_when_the_card_is_disabled(
client, auth_headers, db_session
):
"""A disabled card is still assigned, so it still blocks the deletion."""
from app.model.models import Card
group_id = _group_with_card(client, auth_headers, db_session, "group_disabled_card")
card = db_session.exec(select(Card).where(Card.group_id == group_id)).one()
card.enabled = False
db_session.add(card)
db_session.commit()
response = client.delete(f"/api/v1/groups/{group_id}", headers=auth_headers)
assert response.status_code == 409
def test_group_delete_allowed_after_its_last_card_is_gone(
client, auth_headers, db_session
):
"""Deleting the group's cards first unblocks the group deletion."""
from app.model.models import Card
group_id = _group_with_card(client, auth_headers, db_session, "group_to_empty")
for card in db_session.exec(select(Card).where(Card.group_id == group_id)).all():
db_session.delete(card)
db_session.commit()
response = client.delete(f"/api/v1/groups/{group_id}", headers=auth_headers)
assert response.status_code == 200
response = client.get("/api/v1/groups/", headers=auth_headers)
assert not any(group["id"] == group_id for group in response.json())
def test_card_create_without_group_id_is_rejected(client, auth_headers):
"""POST /cards/ requires a group_id, so a new card cannot start out orphaned."""
for body in (
{"name": "no_group_card", "key": "k", "card_serial": "00:00:00:00:00:00:00"},
{
"name": "null_group_card",
"key": "k",
"card_serial": "00:00:00:00:00:00:00",
"group_id": None,
},
):
response = client.post("/api/v1/cards/", json=body, headers=auth_headers)
assert response.status_code == 422
assert "group_id" in str(response.json()["detail"])
def test_patch_cannot_orphan_a_card_by_nulling_group_id(
client, auth_headers, db_session
):
"""update_card() dumps with exclude_unset+exclude_none, so an explicit null is
dropped and never reaches sqlmodel_update. A card can be moved between groups
but never unassigned through the API."""
from app.model.models import Card
group_id = _group_with_card(client, auth_headers, db_session, "patch_null_group")
card = db_session.exec(select(Card).where(Card.group_id == group_id)).one()
response = client.patch(
f"/api/v1/cards/{card.id}", json={"group_id": None}, headers=auth_headers
)
assert response.status_code == 200
assert response.json()["group_id"] == group_id
db_session.expire_all()
assert db_session.get(Card, card.id).group_id == group_id
def test_patch_cannot_orphan_a_card_by_omitting_group_id(
client, auth_headers, db_session
):
"""A PATCH that only touches other fields leaves group_id at its old value."""
from app.model.models import Card
group_id = _group_with_card(client, auth_headers, db_session, "patch_no_group")
card = db_session.exec(select(Card).where(Card.group_id == group_id)).one()
response = client.patch(
f"/api/v1/cards/{card.id}", json={"enabled": False}, headers=auth_headers
)
assert response.status_code == 200
assert response.json()["group_id"] == group_id
db_session.expire_all()
assert db_session.get(Card, card.id).group_id == group_id
def test_card_without_group_id_cannot_be_written_to_the_db(db_session):
"""Card.group_id is not nullable anymore. Neither Pydantic nor SQLModel validate
annotations (Card(group_id=None) constructs fine), so the NOT NULL column built
from the model is what actually keeps cards from being orphaned."""
from sqlalchemy import exc as sa_exc
from app.model.models import Card
card = Card(
key="orphan-key",
card_serial="00:00:00:00:00:00:00",
name="orphan_card",
enabled=True,
group_id=None,
last_used=datetime.now(UTC),
)
db_session.add(card)
with pytest.raises(sa_exc.IntegrityError) as excinfo:
db_session.commit()
assert "NOT NULL constraint failed: card.group_id" in str(excinfo.value)
db_session.rollback()
assert (
db_session.exec(select(Card).where(Card.name == "orphan_card")).one_or_none()
is None
)
def test_delete_nonexistent_group(client, auth_headers):
"""Test deleting a non-existent group."""
response = client.delete("/api/v1/groups/99999", headers=auth_headers)
assert response.status_code == 404
def test_group_operations_by_non_admin(client, user_auth_headers):
"""Test that non-admin users cannot perform group operations."""
# Try to create a group
response = client.post(
"/api/v1/groups/", json={"name": "test"}, headers=user_auth_headers
)
assert response.status_code == 403
# Try to get groups
response = client.get("/api/v1/groups/", headers=user_auth_headers)
assert response.status_code == 403