142 lines
6.6 KiB
Python
142 lines
6.6 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""Phase 8b gegen PostgreSQL: Filter, Teilnehmerlisten, Export, Löschen von Antworten (CI)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
import zipfile
|
|
from datetime import UTC, datetime, timedelta
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
|
|
from fastapi.testclient import TestClient
|
|
from helpers import new_client, token_for
|
|
from sqlalchemy import select, update
|
|
from sqlalchemy.orm import Session
|
|
from test_forms import add_question, creator, fill, form_row, participant, question_ids
|
|
from test_phase5 import slot_form
|
|
|
|
from surveybox import db
|
|
from surveybox.models import AuditEvent, Response
|
|
|
|
pytestmark = pytest.mark.db
|
|
|
|
|
|
def prepare(app: Any) -> tuple[TestClient, str, str, int, int, list[str]]:
|
|
carla = creator(app)
|
|
pid, token, slot_q, options = slot_form(carla, capacity="1", waitlist=True)
|
|
add_question(carla, pid, "participant_name", label="Name", email_mode="optional",
|
|
personal="on")
|
|
name_q = question_ids(pid)[-1]
|
|
fill(new_client(app), token, {f"q{slot_q}": options[0], f"q{name_q}_first": "Bernd",
|
|
f"q{name_q}_last": "Krause", f"q{name_q}_email": "=b@x.de"})
|
|
fill(new_client(app), token, {f"q{slot_q}": options[0], f"q{name_q}_first": "Carla",
|
|
f"q{name_q}_last": "Kurz"})
|
|
fill(participant(app), token, {f"q{slot_q}": options[1], f"q{name_q}_first": "Paul",
|
|
f"q{name_q}_last": "Peters"})
|
|
return carla, pid, token, slot_q, name_q, options
|
|
|
|
|
|
def export(client: TestClient, pid: str, **data: str) -> Any:
|
|
csrf = token_for(client, f"/forms/{pid}/responses")
|
|
return client.post(f"/forms/{pid}/responses/export", data={"csrf_token": csrf, **data})
|
|
|
|
|
|
def test_lists_filters_and_summary(app: Any) -> None:
|
|
carla, pid, _, slot_q, _, options = prepare(app)
|
|
page = carla.get(f"/forms/{pid}/responses").text
|
|
# Teilnehmerliste: Früh mit Bernd, Carla auf der Warteliste; Spät mit Paul
|
|
assert "Bernd Krause" in page and "Carla Kurz" in page and "Paul Peters" in page
|
|
filtered = carla.get(f"/forms/{pid}/responses?answer={slot_q}:{options[1]}").text
|
|
assert "1 of 3 answer matches the filter" in filtered
|
|
assert "Paul Peters" in filtered and "Bernd Krause" not in filtered
|
|
tomorrow = (datetime.now(UTC) + timedelta(days=1)).date().isoformat()
|
|
assert "0 of 3 answers" in carla.get(f"/forms/{pid}/responses?from={tomorrow}").text
|
|
# Unbekannter Filter wird ignoriert
|
|
assert "3 answers so far" in carla.get(f"/forms/{pid}/responses?answer=999:x").text
|
|
|
|
|
|
def test_csv_and_xlsx_export(app: Any) -> None:
|
|
carla, pid, _, _, _, _ = prepare(app)
|
|
resp = export(carla, pid, format="csv")
|
|
assert resp.status_code == 200 and "attachment" in resp.headers["content-disposition"]
|
|
text = resp.content.decode("utf-8-sig")
|
|
rows = list(csv.reader(io.StringIO(text), delimiter=";"))
|
|
assert rows[0][:4] == ["No.", "Submitted", "Changed", "Participant"]
|
|
assert "Name: First name" in rows[0] and "Name: Email address" in rows[0]
|
|
assert len(rows) == 4
|
|
assert any("'=b@x.de" in cell for cell in rows[1]) # Formel entschärft
|
|
assert any("(waiting list)" in cell for row in rows for cell in row)
|
|
# Ohne personenbezogene Daten: keine Namensspalten, kein Kontoname
|
|
lean = export(carla, pid, format="csv", personal="off").content.decode("utf-8-sig")
|
|
assert "Krause" not in lean and "Participant" not in lean.splitlines()[0]
|
|
# Gefiltert und als XLSX mit Info-Blatt und Logo
|
|
resp = export(carla, pid, format="xlsx", answer="")
|
|
with zipfile.ZipFile(io.BytesIO(resp.content)) as z:
|
|
assert "xl/worksheets/sheet2.xml" not in z.namelist()
|
|
assert any(n.startswith("xl/media/") for n in z.namelist())
|
|
assert "Krause" in z.read("xl/worksheets/sheet1.xml").decode()
|
|
with Session(db.get_engine()) as s:
|
|
details = [e.details for e in s.scalars(
|
|
select(AuditEvent).where(AuditEvent.action == "form.exported"))]
|
|
assert [d["format"] for d in details] == ["csv", "csv", "xlsx"] # type: ignore[index]
|
|
assert details[1]["personal"] is False # type: ignore[index]
|
|
|
|
|
|
def test_browse_and_delete_answer(app: Any) -> None:
|
|
carla, pid, _, _, _, _ = prepare(app)
|
|
with Session(db.get_engine()) as s:
|
|
first = s.scalar(select(Response).where(Response.form_id == form_row(pid).id)
|
|
.order_by(Response.submitted_at, Response.id))
|
|
assert first is not None
|
|
rid = first.public_id
|
|
s.execute(update(Response).where(Response.id == first.id).values(
|
|
submitted_at=datetime.now(UTC) - timedelta(hours=1)))
|
|
s.commit()
|
|
page = carla.get(f"/forms/{pid}/responses/{rid}").text
|
|
assert "Next" in page and "Delete answer" in page
|
|
csrf = token_for(carla, f"/forms/{pid}/responses/{rid}")
|
|
resp = carla.post(f"/forms/{pid}/responses/{rid}/delete",
|
|
data={"csrf_token": csrf, "confirm": "on"})
|
|
assert resp.status_code == 303 and "response_deleted" in resp.headers["location"]
|
|
page = carla.get(f"/forms/{pid}/responses").text
|
|
assert "Bernd Krause" not in page
|
|
# Carla rückt von der Warteliste nach
|
|
assert "2 answers so far" in page
|
|
|
|
|
|
def test_invited_people_without_response_are_listed(app: Any) -> None:
|
|
from helpers import login
|
|
|
|
from surveybox.models import Form, FormAccess, FormAccessEntry, UserAccount
|
|
|
|
carla = creator(app)
|
|
pid, token, slot_q, options = slot_form(carla, capacity="")
|
|
participant(app) # paul
|
|
participant(app, "olga@example.de")
|
|
with Session(db.get_engine()) as s:
|
|
form = s.get(Form, form_row(pid).id)
|
|
assert form is not None
|
|
users = {u.email: u.id for u in s.scalars(select(UserAccount))}
|
|
for email in ("paul@example.de", "olga@example.de"):
|
|
s.add(FormAccessEntry(form_id=form.id, user_id=users[email]))
|
|
form.access = FormAccess.RESTRICTED
|
|
s.commit()
|
|
paul = new_client(app)
|
|
login(paul, "paul@example.de")
|
|
assert fill(paul, token, {f"q{slot_q}": options[0]}).status_code == 303
|
|
page = carla.get(f"/forms/{pid}/responses").text
|
|
assert "1 invited person has not responded yet" in page
|
|
assert "no response yet" in page and "received" in page
|
|
missing = carla.get(f"/forms/{pid}/responses?missing=1").text
|
|
assert "no response yet" in missing and "received" not in missing
|
|
# Im Export ebenfalls, aber nicht ohne personenbezogene Daten
|
|
full = export(carla, pid, format="csv").content.decode("utf-8-sig")
|
|
assert "no response yet" in full
|
|
lean = export(carla, pid, format="csv", personal="off").content.decode("utf-8-sig")
|
|
assert "no response yet" not in lean
|