Files
marco.morath 94466378c7
CI / audit (push) Skipped
CI / checks (push) Successful in 4m13s
CI / image (push) Successful in 1m16s
fix:Umfrageergebnisse und Archivierung
2026-11-26 15:19:43 +01:00

424 lines
16 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Formulare: Anlegen, Ausfüllen, Zugriffsarten, Anonymität, Rechte (CI, PostgreSQL)."""
from __future__ import annotations
import uuid
from typing import Any
import pytest
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient
from helpers import login, make_user, new_client, token_for
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from surveybox import db
from surveybox.accounts import groups
from surveybox.models import (
Answer,
Form,
FormParticipation,
Response,
Role,
UserAccount,
)
pytestmark = pytest.mark.db
# ---------------------------------------------------------------------------
# Hilfen
# ---------------------------------------------------------------------------
def creator(app: Any, email: str = "carla@example.de") -> TestClient:
make_user(Role.CREATOR, email)
client = new_client(app)
assert login(client, email).status_code == 303
return client
def participant(app: Any, email: str = "paul@example.de") -> TestClient:
make_user(Role.PARTICIPANT, email)
client = new_client(app)
assert login(client, email).status_code == 303
return client
def create_form(client: TestClient, title: str = "Sommerfest") -> str:
csrf = token_for(client, "/forms")
resp = client.post("/forms", data={"title": title, "csrf_token": csrf})
assert resp.status_code == 303, resp.text
return resp.headers["location"].rsplit("/", 1)[-1]
def add_question(client: TestClient, pid: str, type_key: str, **fields: Any) -> None:
csrf = token_for(client, f"/forms/{pid}/questions/new?type={type_key}")
data = {"csrf_token": csrf, **fields}
resp = client.post(f"/forms/{pid}/questions/new?type={type_key}", data=data)
assert resp.status_code == 303, resp.text
def save_settings(client: TestClient, pid: str, **overrides: Any) -> Any:
csrf = token_for(client, f"/forms/{pid}/settings")
data: dict[str, Any] = {
"csrf_token": csrf,
"title": "Sommerfest",
"access": "users",
"allow_edit": "until_close",
"deletion_mode": "anonymize",
"guest_email": "none",
"results_visibility": "never",
}
data.update(overrides)
return client.post(f"/forms/{pid}/settings", data=data)
def set_status(client: TestClient, pid: str, status: str) -> Any:
csrf = token_for(client, f"/forms/{pid}")
return client.post(f"/forms/{pid}/status", data={"status": status, "csrf_token": csrf})
def form_row(pid: str) -> Form:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
s.expunge(form)
return form
def question_ids(pid: str) -> list[int]:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
return [q.id for q in form.questions]
def response_count(pid: str) -> int:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
return s.scalar(select(func.count()).where(Response.form_id == form.id)) or 0
def simple_form(client: TestClient, **settings: Any) -> tuple[str, str, list[int]]:
"""Formular mit Pflicht-Textfrage und Einfachauswahl, veröffentlicht."""
pid = create_form(client)
add_question(client, pid, "short_text", label="Ihr Name", required="on", max_length="50")
add_question(
client, pid, "single_choice", label="Lieblingsessen",
option_id=["", "", ""], option_label=["Pizza", "Salat", ""], display="radio",
)
if settings:
assert save_settings(client, pid, **settings).status_code == 303
assert set_status(client, pid, "open").status_code == 303
return pid, form_row(pid).share_token, question_ids(pid)
def option_ids(pid: str, qid: int) -> list[str]:
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
question = next(q for q in form.questions if q.id == qid)
return [o["id"] for o in question.config["options"]]
def fill(client: TestClient, token: str, data: dict[str, Any], path: str = "") -> Any:
csrf = token_for(client, f"/f/{token}{path}")
return client.post(f"/f/{token}{path}", data={"csrf_token": csrf, **data})
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
def test_create_form_and_questions(app: Any) -> None:
client = creator(app)
pid = create_form(client, " Umfrage Herbst ")
assert form_row(pid).title == "Umfrage Herbst"
add_question(client, pid, "heading", label="Teil 1")
add_question(client, pid, "rating", label="Wie war es?", scale_max="7")
add_question(
client, pid, "multiple_choice", label="Was?",
option_id=["", ""], option_label=["A", "B"], min_select="0", max_select="2",
)
page = client.get(f"/forms/{pid}")
assert page.status_code == 200
assert "Wie war es?" in page.text
ids = question_ids(pid)
assert len(ids) == 3
# Zu wenige Optionen werden abgelehnt
csrf = token_for(client, f"/forms/{pid}/questions/new?type=ranking")
resp = client.post(
f"/forms/{pid}/questions/new?type=ranking",
data={"csrf_token": csrf, "label": "Rang", "option_id": [""], "option_label": ["nur eine"]},
)
assert resp.status_code == 400
assert "at least two options" in resp.text
# Verschieben: die letzte Frage nach oben
csrf = token_for(client, f"/forms/{pid}")
resp = client.post(
f"/forms/{pid}/questions/{ids[2]}/move", data={"direction": "up", "csrf_token": csrf}
)
assert resp.status_code == 303
assert question_ids(pid) == [ids[0], ids[2], ids[1]]
# Vorschau rendert das Formular ohne Absende-Knopf
preview = client.get(f"/forms/{pid}/preview")
assert preview.status_code == 200
assert 'type="submit">Submit' not in preview.text
def test_publish_needs_input_question(app: Any) -> None:
client = creator(app)
pid = create_form(client)
add_question(client, pid, "info", label="Nur Text")
resp = set_status(client, pid, "open")
assert resp.status_code == 400
assert form_row(pid).status == "draft"
def test_draft_is_not_reachable(app: Any) -> None:
client = creator(app)
pid = create_form(client)
token = form_row(pid).share_token
guest = new_client(app)
assert guest.get(f"/f/{token}").status_code == 404
assert guest.get("/f/doesnotexist").status_code == 404
def test_fill_as_user_once_and_edit(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, q_food) = simple_form(owner)
pizza = option_ids(pid, q_food)[0]
user = participant(app)
# Startseite zeigt das offene Formular
assert "Sommerfest" in user.get("/").text
resp = fill(user, token, {f"q{q_name}": "Paul", f"q{q_food}": pizza})
assert resp.status_code == 303
assert resp.headers["location"] == f"/f/{token}/thanks"
assert response_count(pid) == 1
# Zweiter Aufruf: bereits teilgenommen, Ändern möglich
again = user.get(f"/f/{token}")
assert "already filled in" in again.text
assert f"/f/{token}/edit" in again.text
# Doppeltes Absenden (z. B. altes Formular im Browser) legt nichts an
csrf = token_for(user, "/")
user.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Paul"})
assert response_count(pid) == 1
# Ändern
edit = user.get(f"/f/{token}/edit")
assert edit.status_code == 200
assert 'value="Paul"' in edit.text
resp = fill(user, token, {f"q{q_name}": "Paul Neu"}, path="/edit")
assert resp.status_code == 303
with Session(db.get_engine()) as s:
texts = set(s.scalars(select(Answer.value_text).where(Answer.question_id == q_name)))
assert texts == {"Paul Neu"}
# Auswahl wurde entfernt, weil im neuen Absenden leer
assert s.scalar(select(func.count()).where(Answer.question_id == q_food)) == 0
def test_users_access_requires_login(app: Any) -> None:
owner = creator(app)
_, token, _ = simple_form(owner)
guest = new_client(app)
resp = guest.get(f"/f/{token}")
assert resp.status_code == 303
assert resp.headers["location"].startswith("/login")
def test_validation_errors_keep_input(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
add_question(owner, pid, "short_text", label="Name", required="on", max_length="50")
add_question(owner, pid, "number", label="Anzahl", min="1", max="10", decimals="0")
add_question(owner, pid, "email", label="Mail")
assert save_settings(owner, pid, access="link").status_code == 303
assert set_status(owner, pid, "open").status_code == 303
token = form_row(pid).share_token
q_name, q_num, q_mail = question_ids(pid)
guest = new_client(app)
resp = fill(guest, token, {f"q{q_name}": "", f"q{q_num}": "12", f"q{q_mail}": "kein@"})
assert resp.status_code == 400
assert "Please answer this question." in resp.text
assert "The number is too large." in resp.text
assert "Please enter a valid email address." in resp.text
assert 'value="12"' in resp.text
assert response_count(pid) == 0
resp = fill(guest, token, {f"q{q_name}": "Gast", f"q{q_num}": "3", f"q{q_mail}": ""})
assert resp.status_code == 303
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
assert response.user_id is None
numbers = list(s.scalars(select(Answer.value_number).where(Answer.question_id == q_num)))
assert [float(n) for n in numbers] == [3.0]
def test_link_password(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link_password", link_password="geheim1")
guest = new_client(app)
page = guest.get(f"/f/{token}")
assert page.status_code == 200
assert 'name="password"' in page.text
csrf = token_for(guest, f"/f/{token}")
wrong = guest.post(f"/f/{token}/password", data={"password": "falsch", "csrf_token": csrf})
assert wrong.status_code == 400
right = guest.post(f"/f/{token}/password", data={"password": "geheim1", "csrf_token": csrf})
assert right.status_code == 303
page = guest.get(f"/f/{token}")
assert f'name="q{q_name}"' in page.text
assert fill(guest, token, {f"q{q_name}": "Gast"}).status_code == 303
assert response_count(pid) == 1
# Neues Passwort macht alte Freischaltungen ungültig
changed = save_settings(owner, pid, access="link_password", link_password="anderes2")
assert changed.status_code == 303
assert 'name="password"' in guest.get(f"/f/{token}").text
def test_link_password_needs_password(app: Any) -> None:
owner = creator(app)
pid = create_form(owner)
resp = save_settings(owner, pid, access="link_password")
assert resp.status_code == 400
assert form_row(pid).access == "users"
def test_restricted_access_via_group(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner)
member_client = participant(app, "mia@example.de")
outsider = participant(app, "otto@example.de")
with Session(db.get_engine()) as s:
member = s.scalar(select(UserAccount).where(UserAccount.email == "mia@example.de"))
assert member is not None
group = groups.create(s, "Festausschuss", "", actor_id=member.id)
groups.add_member(s, group, member, actor_id=member.id)
s.commit()
group_pid = str(group.public_id)
resp = save_settings(owner, pid, access="restricted")
assert resp.status_code == 303
assert resp.headers["location"] == f"/forms/{pid}/access"
csrf = token_for(owner, f"/forms/{pid}/access")
resp = owner.post(f"/forms/{pid}/access", data={"groups": [group_pid], "csrf_token": csrf})
assert resp.status_code == 303
assert outsider.get(f"/f/{token}").status_code == 403
assert "Sommerfest" not in outsider.get("/").text
assert member_client.get(f"/f/{token}").status_code == 200
assert fill(member_client, token, {f"q{q_name}": "Mia"}).status_code == 303
def test_anonymous_participation(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, anonymous="on")
user = participant(app)
assert fill(user, token, {f"q{q_name}": "geheim"}).status_code == 303
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
assert response.user_id is None
assert s.scalar(select(func.count()).select_from(FormParticipation)) == 1
again = user.get(f"/f/{token}")
assert "already filled in" in again.text
assert "/edit" not in again.text
assert user.get(f"/f/{token}/edit").status_code == 303
# Anonymität lässt sich nach der ersten Antwort nicht mehr abschalten
resp = save_settings(owner, pid)
assert resp.status_code == 400
assert form_row(pid).anonymous is True
def test_consent_required(app: Any) -> None:
owner = creator(app)
_, token, (q_name, _) = simple_form(
owner, access="link", require_consent="on", consent_text="Ich willige ein."
)
guest = new_client(app)
resp = fill(guest, token, {f"q{q_name}": "Gast"})
assert resp.status_code == 400
assert "Please confirm the consent." in resp.text
assert fill(guest, token, {f"q{q_name}": "Gast", "consent": "on"}).status_code == 303
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
assert response.consent_at is not None
def test_closed_form(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link")
assert set_status(owner, pid, "closed").status_code == 303
guest = new_client(app)
page = guest.get(f"/f/{token}")
assert "This form is completed" in page.text
csrf = token_for(guest, "/login") # die Seite des beendeten Formulars hat kein Formular
guest.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Zu spät"})
assert response_count(pid) == 0
def test_responses_view_and_permissions(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner)
user = participant(app)
assert fill(user, token, {f"q{q_name}": "Antwort von Paul"}).status_code == 303
listing = owner.get(f"/forms/{pid}/responses")
assert listing.status_code == 200
with Session(db.get_engine()) as s:
response = s.scalar(select(Response))
assert response is not None
rid = str(response.public_id)
assert rid in listing.text
detail = owner.get(f"/forms/{pid}/responses/{rid}")
assert "Antwort von Paul" in detail.text
# Teilnehmende und fremde Ersteller sehen nichts
assert pid not in user.get("/forms").text
assert user.get(f"/forms/{pid}/responses").status_code == 403
other = creator(app, "olga@example.de")
assert other.get(f"/forms/{pid}").status_code == 403
assert other.get(f"/forms/{pid}/responses/{rid}").status_code == 403
assert pid not in other.get("/forms").text
def test_delete_form(app: Any) -> None:
owner = creator(app)
pid, token, (q_name, _) = simple_form(owner, access="link")
guest = new_client(app)
assert fill(guest, token, {f"q{q_name}": "Gast"}).status_code == 303
csrf = token_for(owner, f"/forms/{pid}/settings")
assert owner.post(f"/forms/{pid}/delete", data={"csrf_token": csrf}).status_code == 400
resp = owner.post(f"/forms/{pid}/delete", data={"csrf_token": csrf, "confirm": "on"})
assert resp.status_code == 303
with Session(db.get_engine()) as s:
assert s.scalar(select(func.count()).select_from(Form)) == 0
assert s.scalar(select(func.count()).select_from(Response)) == 0
assert s.scalar(select(func.count()).select_from(Answer)) == 0
assert guest.get(f"/f/{token}").status_code == 404