import re from datetime import date import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine, select from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import StaticPool from app.database import Base, get_db from app.main import app from app.models import Assignment, MonthlyPattern, NotificationLog, RotationMember, Schedule, SwapRequest, User from app.scheduling import ensure_month_assignments from app.security import hash_password CSRF_RE = re.compile(r'name="csrf_token" value="([^"]+)"') YEAR = 2026 MONTH = 10 @pytest.fixture() def db(): engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool) Base.metadata.create_all(engine) session = sessionmaker(bind=engine, expire_on_commit=False, autoflush=False)() try: yield session finally: session.close() @pytest.fixture() def client(db): def override_get_db(): yield db app.dependency_overrides[get_db] = override_get_db try: yield TestClient(app) finally: app.dependency_overrides.pop(get_db, None) def seed(db): night = Schedule( name="Noite", slug="night", schedule_type="fixed", weekdays="0,1,2,3,4,5,6", label_time="Noite", requires_manager_approval=True, is_active=True, ) sat = Schedule( name="Almoço - Sábados", slug="saturday-lunch", schedule_type="rotation", weekdays="5", label_time="Lunch", requires_manager_approval=True, is_active=True, rotation_anchor_date=date(2026, 1, 3), ) sun = Schedule( name="Almoço - Domingo", slug="sunday-lunch", schedule_type="rotation", weekdays="6", label_time="Lunch", requires_manager_approval=True, is_active=True, rotation_anchor_date=date(2026, 1, 4), ) ana = User(name="Ana", is_active=True, notify_email=False) bruno = User(name="Bruno", is_active=True, notify_email=False) admin = User( name="Admin", username="admin", password_hash=hash_password("admin-password"), is_active=True, is_admin=True, ) db.add_all([night, sat, sun, ana, bruno, admin]) db.flush() db.add_all( [ RotationMember(schedule_id=sat.id, user_id=ana.id, position=0), RotationMember(schedule_id=sat.id, user_id=bruno.id, position=1), RotationMember(schedule_id=sun.id, user_id=bruno.id, position=0), ] ) db.commit() return night, sat, sun, ana, bruno, admin def sign_in(client: TestClient) -> str: token = CSRF_RE.search(client.get("/login").text).group(1) client.post( "/login", data={"username": "admin", "password": "admin-password", "csrf_token": token}, follow_redirects=True, ) return CSRF_RE.search(client.get("/admin/schedules").text).group(1) def assignment_on(db, schedule: Schedule, day: date) -> Assignment: row = db.scalar( select(Assignment).where(Assignment.schedule_id == schedule.id, Assignment.date == day) ) assert row is not None return row def test_night_page_is_a_single_repeating_pattern_with_no_month_picker(client, db): night, _, _, _, _, _ = seed(db) sign_in(client) page = client.get(f"/admin/schedules/{night.id}").text for day in range(1, 32): assert f'name="day_{day}"' in page assert "Guardar padrão" in page assert "Repete todos os meses" in page assert "Previous" not in page assert "Next →" not in page assert f"year={YEAR}" not in page def test_saving_the_pattern_fills_every_month(client, db): night, _, _, ana, bruno, _ = seed(db) token = sign_in(client) response = client.post( f"/admin/schedules/{night.id}/pattern", data={"csrf_token": token, "day_1": ana.id, "day_2": bruno.id, "day_31": ana.id}, follow_redirects=False, ) assert response.status_code == 303 assert response.headers["location"] == f"/admin/schedules/{night.id}" for year, month in ((2026, 11), (2027, 3)): ensure_month_assignments(db, year, month) db.expire_all() assert assignment_on(db, night, date(year, month, 1)).user_id == ana.id assert assignment_on(db, night, date(year, month, 2)).user_id == bruno.id assert assignment_on(db, night, date(year, month, 5)).user_id is None # February has no 31st, so that entry is simply not used. ensure_month_assignments(db, 2027, 2) db.expire_all() assert assignment_on(db, night, date(2027, 2, 28)).user_id is None assert assignment_on(db, night, date(2027, 2, 1)).user_id == ana.id def test_changing_the_pattern_never_rewrites_existing_assignments(client, db): night, _, _, ana, _, _ = seed(db) ensure_month_assignments(db, 2026, 11) db.expire_all() assert assignment_on(db, night, date(2026, 11, 1)).user_id is None # Pattern added after the rows already exist. db.add(MonthlyPattern(schedule_id=night.id, day_of_month=1, user_id=ana.id)) db.commit() ensure_month_assignments(db, 2026, 11) db.expire_all() assert assignment_on(db, night, date(2026, 11, 1)).user_id is None # A month that did not exist yet picks the pattern up. ensure_month_assignments(db, 2026, 12) db.expire_all() assert assignment_on(db, night, date(2026, 12, 1)).user_id == ana.id def test_assigning_on_the_saturday_page_saves_only_saturday_rows(client, db): night, sat, sun, ana, bruno, _ = seed(db) ensure_month_assignments(db, YEAR, MONTH) saturday = assignment_on(db, sat, date(2026, 10, 3)) saturday.user_id = None sunday = assignment_on(db, sun, date(2026, 10, 4)) sunday.user_id = bruno.id db.commit() token = sign_in(client) response = client.post( f"/admin/schedules/{sat.id}/assignments", data={ "csrf_token": token, "year": YEAR, "month": MONTH, f"assignment_{saturday.id}": bruno.id, }, follow_redirects=False, ) assert response.status_code == 303 assert response.headers["location"] == f"/admin/schedules/{sat.id}?year={YEAR}&month={MONTH}" db.expire_all() assert assignment_on(db, sat, date(2026, 10, 3)).user_id == bruno.id # Night and Sunday rows are untouched by the Saturday form. assert assignment_on(db, night, date(2026, 10, 5)).user_id is None assert assignment_on(db, sun, date(2026, 10, 4)).user_id == bruno.id def test_saving_the_pattern_fills_unassigned_nights_of_this_month(client, db): night, _, _, ana, _, _ = seed(db) sign_in(client) # signing in renders the rota, which generates this month ensure_month_assignments(db, date.today().year, date.today().month) db.expire_all() today_row = assignment_on(db, night, date.today()) assert today_row.user_id is None token = CSRF_RE.search(client.get(f"/admin/schedules/{night.id}").text).group(1) client.post( f"/admin/schedules/{night.id}/pattern", data={"csrf_token": token, f"day_{date.today().day}": ana.id}, follow_redirects=False, ) db.expire_all() assert assignment_on(db, night, date.today()).user_id == ana.id def test_saving_the_pattern_leaves_assigned_nights_alone(client, db): night, _, _, ana, bruno, _ = seed(db) sign_in(client) ensure_month_assignments(db, date.today().year, date.today().month) today_row = assignment_on(db, night, date.today()) today_row.user_id = bruno.id today_row.source = "manual" db.commit() token = CSRF_RE.search(client.get(f"/admin/schedules/{night.id}").text).group(1) client.post( f"/admin/schedules/{night.id}/pattern", data={"csrf_token": token, f"day_{date.today().day}": ana.id}, follow_redirects=False, ) db.expire_all() assert assignment_on(db, night, date.today()).user_id == bruno.id def test_saturday_page_only_shows_saturdays(client, db): _, sat, _, _, _, _ = seed(db) sign_in(client) page = client.get(f"/admin/schedules/{sat.id}?year={YEAR}&month={MONTH}").text assert page.count("assignment_") == len([d for d in range(1, 32) if date(2026, 10, d).weekday() == 5]) assert "Almoço - Domingo" in page # listed under other schedules assert "Guardar Outubro" in page def test_month_page_redirects_to_the_schedules_hub(client, db): seed(db) sign_in(client) response = client.get("/admin/month", follow_redirects=False) assert response.status_code == 303 assert response.headers["location"] == "/admin/schedules" def test_apply_rotation_updates_only_automatic_rows_in_selected_schedule_and_month(client, db): night, sat, sun, ana, bruno, admin = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) ensure_month_assignments(db, YEAR, MONTH + 1) manual = assignment_on(db, sat, date(YEAR, MONTH, 10)) manual.user_id, manual.source = admin.id, "manual" swapped = assignment_on(db, sat, date(YEAR, MONTH, 17)) swapped.user_id, swapped.source = bruno.id, "swap" unassigned = assignment_on(db, sat, date(YEAR, MONTH, 24)) unassigned.user_id = None first = assignment_on(db, sat, date(YEAR, MONTH, 3)) assert first.user_id == bruno.id first.note = "Keep this note" db.commit() untouched = { row.id: (row.user_id, row.source) for row in db.scalars(select(Assignment)).all() if row.schedule_id != sat.id or row.date.month != MONTH or row.source != "generated" } members = db.scalars(select(RotationMember).where( RotationMember.schedule_id == sat.id ).order_by(RotationMember.position)).all() members[0].position = 99 db.flush() members[1].position = 0 db.flush() members[0].position = 1 db.commit() # Editing order alone leaves the published assignment stable. ensure_month_assignments(db, YEAR, MONTH) assert db.get(Assignment, first.id).user_id == bruno.id response = client.post(f"/admin/schedules/{sat.id}/apply-rotation", data={ "csrf_token": token, "year": YEAR, "month": MONTH, }, follow_redirects=False) assert response.status_code == 303 assert response.headers["location"] == f"/admin/schedules/{sat.id}?year={YEAR}&month={MONTH}" db.expire_all() assert db.get(Assignment, first.id).user_id == ana.id assert db.get(Assignment, first.id).note == "Keep this note" # The preserved swap on the 17th supplies Bruno as the reference; # in the reordered Bruno -> Ana rotation, the 24th goes to Ana. assert db.get(Assignment, unassigned.id).user_id == ana.id for assignment_id, expected in untouched.items(): row = db.get(Assignment, assignment_id) assert (row.user_id, row.source) == expected log_count = len(db.scalars(select(NotificationLog)).all()) client.post(f"/admin/schedules/{sat.id}/apply-rotation", data={ "csrf_token": token, "year": YEAR, "month": MONTH, }) assert len(db.scalars(select(NotificationLog)).all()) == log_count def test_apply_rotation_creates_only_missing_dates_for_selected_schedule(client, db): _, sat, _, _, _, _ = seed(db) token = sign_in(client) response = client.post(f"/admin/schedules/{sat.id}/apply-rotation", data={ "csrf_token": token, "year": 2027, "month": 1, }, follow_redirects=False) assert response.status_code == 303 rows = db.scalars(select(Assignment).where(Assignment.date >= date(2027, 1, 1))).all() assert len(rows) == 5 assert all(row.schedule_id == sat.id and row.date.weekday() == 5 and row.user_id is not None for row in rows) @pytest.mark.parametrize("status", ["open", "pending_approval"]) @pytest.mark.parametrize("action", ["apply-rotation", "use-rotation"]) def test_rotation_actions_cancel_stale_requests_and_notify_after_reassignment(client, db, status, action): _, sat, _, ana, bruno, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) # Bruno's date in the seeded order row.user_id = ana.id row.source = "manual" if action == "use-rotation" else "generated" row.note = "Keep assignment history" db.add(SwapRequest(assignment_id=row.id, requester_id=ana.id, accepted_by_id=bruno.id, status=status)) db.commit() url = f"/admin/schedules/{sat.id}/apply-rotation" if action == "apply-rotation" else ( f"/admin/schedules/{sat.id}/assignments/{row.id}/use-rotation" ) response = client.post(url, data={"csrf_token": token, "year": YEAR, "month": MONTH}, follow_redirects=False) assert response.status_code == 303 db.expire_all() restored = db.get(Assignment, row.id) assert (restored.user_id, restored.source, restored.note) == (bruno.id, "generated", "Keep assignment history") request = db.scalar(select(SwapRequest).where(SwapRequest.assignment_id == row.id)) assert request.status == "cancelled" logs = db.scalars(select(NotificationLog)).all() assert {(log.user_id, log.event_type) for log in logs} == { (ana.id, "assignment_changed"), (bruno.id, "assignment_updated"), } def test_use_rotation_removes_override_even_when_person_is_already_correct(client, db): _, sat, _, ana, bruno, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) row.source = "manual" db.add(SwapRequest(assignment_id=row.id, requester_id=bruno.id, target_user_id=ana.id, status="open")) db.commit() client.post(f"/admin/schedules/{sat.id}/assignments/{row.id}/use-rotation", data={"csrf_token": token}) db.expire_all() assert (row.user_id, row.source) == (bruno.id, "generated") assert db.scalar(select(SwapRequest).where(SwapRequest.assignment_id == row.id)).status == "open" assert not db.scalars(select(NotificationLog)).all() def test_reset_unassigned_manual_row_and_apply_later_when_members_become_active(client, db): _, sat, _, ana, bruno, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) row.user_id, row.source = None, "manual" ana.is_active = bruno.is_active = False db.commit() client.post(f"/admin/schedules/{sat.id}/assignments/{row.id}/use-rotation", data={"csrf_token": token}) db.expire_all() assert (row.user_id, row.source) == (None, "generated") ana.is_active = True db.commit() client.post(f"/admin/schedules/{sat.id}/apply-rotation", data={ "csrf_token": token, "year": YEAR, "month": MONTH, }) db.expire_all() assert (row.user_id, row.source) == (ana.id, "generated") def test_rotation_controls_render_regenerate_for_every_row_as_separate_forms(client, db): night, sat, _, _, _, _ = seed(db) sign_in(client) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) row.source = "manual" swapped = assignment_on(db, sat, date(YEAR, MONTH, 10)) swapped.source = "swap" db.commit() page = client.get(f"/admin/schedules/{sat.id}?year={YEAR}&month={MONTH}").text assert "Aplicar rotação em Outubro" in page assert page.count(">Recalcular") == 5 assert f'form="regenerate-{row.id}"' in page assert f'form="regenerate-{swapped.id}"' in page assert f'action="/admin/schedules/{sat.id}/assignments/{row.id}/regenerate"' in page assert page.index(f'id="regenerate-{row.id}"') > page.index("Guardar Outubro") assert "Gerar depois da data" in page assert 'name="after_date" value="2026-09-30"' in page assert 'name="through_date" value="2026-10-31"' in page assert "Aplicar rotação" not in client.get(f"/admin/schedules/{night.id}").text def test_rotation_actions_reject_invalid_schedule_row_and_month(client, db): night, sat, sun, _, _, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) base = {"csrf_token": token, "year": YEAR, "month": MONTH} assert client.post(f"/admin/schedules/{night.id}/apply-rotation", data=base).status_code == 400 assert client.post(f"/admin/schedules/{sat.id}/apply-rotation", data={**base, "month": 13}).status_code == 400 assert client.post(f"/admin/schedules/{sun.id}/assignments/{row.id}/use-rotation", data=base).status_code == 404 wrong_day = Assignment(schedule_id=sat.id, date=date(YEAR, MONTH, 4), user_id=None, source="manual") db.add(wrong_day) db.commit() assert client.post(f"/admin/schedules/{sat.id}/assignments/{wrong_day.id}/regenerate", data=base).status_code == 400 night_row = assignment_on(db, night, date(YEAR, MONTH, 3)) assert client.post(f"/admin/schedules/{night.id}/assignments/{night_row.id}/regenerate", data=base).status_code == 400 @pytest.mark.parametrize("action", ["apply-rotation", "use-rotation"]) def test_rotation_actions_require_admin_and_csrf(client, db, action): _, sat, _, _, _, _ = seed(db) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) row.source = "manual" member = User(name="Member", username="member", password_hash=hash_password("member-password"), is_active=True) db.add(member) db.commit() url = f"/admin/schedules/{sat.id}/apply-rotation" if action == "apply-rotation" else ( f"/admin/schedules/{sat.id}/assignments/{row.id}/use-rotation" ) data = {"csrf_token": "invalid", "year": YEAR, "month": MONTH} assert client.post(url, data=data).status_code == 401 token = sign_in(client) assert client.post(url, data=data).status_code == 400 client.post("/logout", data={"csrf_token": token}) token = CSRF_RE.search(client.get("/login").text).group(1) client.post("/login", data={"username": "member", "password": "member-password", "csrf_token": token}) assert client.post(url, data={**data, "csrf_token": token}).status_code == 403 def test_use_rotation_selects_next_person_after_previous_actual_assignee(client, db): _, sat, _, ana, bruno, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) carla = User(name="Carla", is_active=True, notify_email=False) db.add(carla) db.flush() db.add(RotationMember(schedule_id=sat.id, user_id=carla.id, position=2)) previous = assignment_on(db, sat, date(YEAR, MONTH, 3)) previous.user_id, previous.source = bruno.id, "manual" target = assignment_on(db, sat, date(YEAR, MONTH, 10)) target.user_id, target.source = ana.id, "manual" db.commit() other_rows = {row.id: (row.user_id, row.source) for row in db.scalars(select(Assignment)).all() if row.id != target.id} response = client.post(f"/admin/schedules/{sat.id}/assignments/{target.id}/use-rotation", data={ "csrf_token": token, }, follow_redirects=False) assert response.status_code == 303 db.expire_all() assert (target.user_id, target.source) == (carla.id, "generated") for assignment_id, expected in other_rows.items(): row = db.get(Assignment, assignment_id) assert (row.user_id, row.source) == expected def test_apply_rotation_continues_chronologically_from_previous_month_and_preserved_override(client, db): _, sat, _, ana, bruno, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) carla = User(name="Carla", is_active=True, notify_email=False) db.add(carla) db.flush() db.add(RotationMember(schedule_id=sat.id, user_id=carla.id, position=2)) db.add(Assignment(schedule_id=sat.id, date=date(YEAR, 9, 26), user_id=bruno.id, source="manual")) preserved = assignment_on(db, sat, date(YEAR, MONTH, 17)) preserved.user_id, preserved.source = carla.id, "swap" db.commit() response = client.post(f"/admin/schedules/{sat.id}/apply-rotation", data={ "csrf_token": token, "year": YEAR, "month": MONTH, }, follow_redirects=False) assert response.status_code == 303 db.expire_all() rows = [assignment_on(db, sat, date(YEAR, MONTH, day)) for day in (3, 10, 17, 24, 31)] assert [row.user_id for row in rows] == [carla.id, ana.id, carla.id, ana.id, bruno.id] assert preserved.source == "swap" @pytest.mark.parametrize("source", ["generated", "manual", "swap"]) def test_regenerate_replaces_any_assignment_source_and_retains_history(client, db, source): _, sat, _, ana, bruno, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) row.user_id, row.source, row.note = ana.id, source, "Keep date history" completed = SwapRequest(assignment_id=row.id, requester_id=bruno.id, accepted_by_id=ana.id, status="approved") stale = SwapRequest(assignment_id=row.id, requester_id=ana.id, target_user_id=bruno.id, status="open") db.add_all([completed, stale]) db.commit() other_rows = {r.id: (r.user_id, r.source) for r in db.scalars(select(Assignment)).all() if r.id != row.id} response = client.post(f"/admin/schedules/{sat.id}/assignments/{row.id}/regenerate", data={ "csrf_token": token, }, follow_redirects=False) assert response.status_code == 303 db.expire_all() assert (row.user_id, row.source, row.note) == (bruno.id, "generated", "Keep date history") assert completed.status == "approved" assert stale.status == "cancelled" for assignment_id, expected in other_rows.items(): current = db.get(Assignment, assignment_id) assert (current.user_id, current.source) == expected def test_generate_after_date_spans_months_with_exclusive_start_and_inclusive_end(client, db): _, sat, _, ana, bruno, admin = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) reference = assignment_on(db, sat, date(YEAR, MONTH, 31)) reference.user_id, reference.source = ana.id, "manual" outdated = Assignment(schedule_id=sat.id, date=date(YEAR, 11, 7), user_id=ana.id, source="generated") swapped = Assignment(schedule_id=sat.id, date=date(YEAR, 11, 14), user_id=bruno.id, source="swap") later = Assignment(schedule_id=sat.id, date=date(YEAR, 11, 28), user_id=admin.id, source="generated") db.add_all([outdated, swapped, later]) db.flush() stale = SwapRequest(assignment_id=outdated.id, requester_id=ana.id, status="pending_approval") db.add(stale) db.commit() untouched = {row.id: (row.user_id, row.source) for row in db.scalars(select(Assignment)).all() if row.id != outdated.id} response = client.post(f"/admin/schedules/{sat.id}/generate-after", data={ "csrf_token": token, "after_date": "2026-10-31", "through_date": "2026-11-21", }, follow_redirects=False) assert response.status_code == 303 assert response.headers["location"] == f"/admin/schedules/{sat.id}?year=2026&month=11" db.expire_all() assert (outdated.user_id, outdated.source) == (bruno.id, "generated") generated = assignment_on(db, sat, date(YEAR, 11, 21)) assert (generated.user_id, generated.source) == (ana.id, "generated") assert stale.status == "cancelled" for assignment_id, expected in untouched.items(): row = db.get(Assignment, assignment_id) assert (row.user_id, row.source) == expected november = db.scalars(select(Assignment).where( Assignment.date >= date(YEAR, 11, 1), Assignment.date <= date(YEAR, 11, 30) )).all() assert len(november) == 4 assert all(row.schedule_id == sat.id for row in november) before_repeat = [(r.id, r.user_id, r.source) for r in november] log_count = len(db.scalars(select(NotificationLog)).all()) client.post(f"/admin/schedules/{sat.id}/generate-after", data={ "csrf_token": token, "after_date": "2026-10-31", "through_date": "2026-11-21", }, follow_redirects=False) db.expire_all() assert [(r.id, r.user_id, r.source) for r in november] == before_repeat assert len(db.scalars(select(NotificationLog)).all()) == log_count def test_generate_after_date_fills_multiple_months_in_order(client, db): _, sat, _, ana, bruno, _ = seed(db) token = sign_in(client) ensure_month_assignments(db, YEAR, MONTH) reference = assignment_on(db, sat, date(YEAR, MONTH, 31)) reference.user_id = bruno.id db.commit() response = client.post(f"/admin/schedules/{sat.id}/generate-after", data={ "csrf_token": token, "after_date": "2026-10-31", "through_date": "2026-12-05", }, follow_redirects=False) assert response.status_code == 303 rows = db.scalars(select(Assignment).where(Assignment.date > date(YEAR, MONTH, 31)).order_by(Assignment.date)).all() assert [r.date for r in rows] == [date(YEAR, 11, day) for day in (7, 14, 21, 28)] + [date(YEAR, 12, 5)] assert [r.user_id for r in rows] == [ana.id, bruno.id, ana.id, bruno.id, ana.id] assert all(r.schedule_id == sat.id and r.source == "generated" for r in rows) @pytest.mark.parametrize("after_date,through_date,status", [ ("2026-10-31", "2026-10-31", 400), ("2026-10-31", "2026-10-01", 400), ("1999-12-30", "2026-10-31", 400), ("2026-10-31", "2101-01-01", 400), ("not-a-date", "2026-10-31", 422), ("2026-10-31", "2026-11-31", 422), ]) def test_generate_after_rejects_invalid_ranges_without_editing_data(client, db, after_date, through_date, status): _, sat, _, _, _, _ = seed(db) token = sign_in(client) snapshot = [(r.id, r.user_id, r.source) for r in db.scalars(select(Assignment)).all()] assert client.post(f"/admin/schedules/{sat.id}/generate-after", data={ "csrf_token": token, "after_date": after_date, "through_date": through_date, }).status_code == status assert [(r.id, r.user_id, r.source) for r in db.scalars(select(Assignment)).all()] == snapshot @pytest.mark.parametrize("action", ["regenerate", "generate-after"]) def test_new_generation_controls_require_admin_and_csrf(client, db, action): night, sat, _, _, _, _ = seed(db) ensure_month_assignments(db, YEAR, MONTH) row = assignment_on(db, sat, date(YEAR, MONTH, 3)) member = User(name="Member", username="member", password_hash=hash_password("member-password"), is_active=True) db.add(member) db.commit() url = f"/admin/schedules/{sat.id}/assignments/{row.id}/regenerate" if action == "regenerate" else ( f"/admin/schedules/{sat.id}/generate-after" ) data = {"csrf_token": "invalid", "after_date": "2026-10-31", "through_date": "2026-11-21"} assert client.post(url, data=data).status_code == 401 token = sign_in(client) assert client.post(url, data=data).status_code == 400 if action == "generate-after": assert client.post(f"/admin/schedules/{night.id}/generate-after", data={**data, "csrf_token": token}).status_code == 400 client.post("/logout", data={"csrf_token": token}) token = CSRF_RE.search(client.get("/login").text).group(1) client.post("/login", data={"username": "member", "password": "member-password", "csrf_token": token}) assert client.post(url, data={**data, "csrf_token": token}).status_code == 403