209 lines
8.6 KiB
Python
209 lines
8.6 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""Phase 4 gegen PostgreSQL: Bedingungen, Seiten, Gruppen beim Anlegen, eigene Video-Quellen."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
|
|
from fastapi.testclient import TestClient
|
|
from helpers import csrf_from, login, make_user, new_client, next_totp, token_for
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
from test_forms import (
|
|
add_question,
|
|
create_form,
|
|
creator,
|
|
fill,
|
|
form_row,
|
|
question_ids,
|
|
save_settings,
|
|
set_status,
|
|
)
|
|
|
|
from surveybox import db
|
|
from surveybox.media import config as media_config
|
|
from surveybox.models import Answer, GroupMember, Question, Role, UserAccount, UserGroup
|
|
|
|
pytestmark = pytest.mark.db
|
|
|
|
|
|
def config_of(qid: int) -> dict[str, Any]:
|
|
with Session(db.get_engine()) as s:
|
|
q = s.get(Question, qid)
|
|
assert q is not None
|
|
return dict(q.config)
|
|
|
|
|
|
def rule_fields(ref: int, op: str, *, option: str = "", text: str = "",
|
|
action: str = "show") -> dict[str, Any]:
|
|
return {"cond_action": action, "cond_match": "all", "rule_q": [str(ref), ""],
|
|
"rule_op": [op, "eq"], "rule_option": [option, ""], "rule_text": [text, ""]}
|
|
|
|
|
|
def conditional_form(owner: TestClient) -> tuple[str, str, int, int, int]:
|
|
"""Ja/Nein, dann Pflicht-Zahl nur bei Ja, dann Seite 2 mit Bemerkung."""
|
|
pid = create_form(owner)
|
|
add_question(owner, pid, "yes_no", label="Kommen Sie?", required="on")
|
|
(q_yes,) = question_ids(pid)
|
|
add_question(owner, pid, "number", label="Wie viele?", required="on", decimals="0",
|
|
**rule_fields(q_yes, "eq", option="yes"))
|
|
add_question(owner, pid, "page_break", label="Seite 2")
|
|
add_question(owner, pid, "short_text", label="Bemerkung")
|
|
assert save_settings(owner, pid, access="link").status_code == 303
|
|
assert set_status(owner, pid, "open").status_code == 303
|
|
q_yes, q_count, _, q_note = question_ids(pid)
|
|
return pid, form_row(pid).share_token, q_yes, q_count, q_note
|
|
|
|
|
|
def test_condition_saved_and_summarised(app: Any) -> None:
|
|
owner = creator(app)
|
|
pid, _, q_yes, q_count, _ = conditional_form(owner)
|
|
condition = config_of(q_count)["condition"]
|
|
assert condition == {"action": "show", "match": "all",
|
|
"rules": [{"q": q_yes, "op": "eq", "value": "yes"}]}
|
|
designer = owner.get(f"/forms/{pid}").text
|
|
assert "Shown if all apply:" in designer
|
|
assert "controls 1 condition" in designer
|
|
|
|
|
|
def test_hidden_question_not_required_and_discarded(app: Any) -> None:
|
|
owner = creator(app)
|
|
_, token, q_yes, q_count, q_note = conditional_form(owner)
|
|
guest = new_client(app)
|
|
page = guest.get(f"/f/{token}").text
|
|
assert "data-cond=" in page and 'class="fill-page"' in page
|
|
|
|
# Ja ohne Zahl: Pflicht
|
|
resp = fill(guest, token, {f"q{q_yes}": "yes"})
|
|
assert resp.status_code == 400
|
|
# Nein und trotzdem eine Zahl geschickt (manipuliert): wird verworfen
|
|
resp = fill(guest, token, {f"q{q_yes}": "no", f"q{q_count}": "7", f"q{q_note}": "Gruß"})
|
|
assert resp.status_code == 303
|
|
with Session(db.get_engine()) as s:
|
|
stored = {a.question_id for a in s.scalars(select(Answer))}
|
|
assert stored == {q_yes, q_note}
|
|
|
|
|
|
def test_rules_only_on_earlier_questions(app: Any) -> None:
|
|
owner = creator(app)
|
|
pid, _, q_yes, q_count, q_note = conditional_form(owner)
|
|
# Erste Frage darf sich nicht auf eine spätere beziehen
|
|
csrf = token_for(owner, f"/forms/{pid}/questions/{q_yes}")
|
|
resp = owner.post(
|
|
f"/forms/{pid}/questions/{q_yes}",
|
|
data={"csrf_token": csrf, "label": "Kommen Sie?", **rule_fields(q_note, "empty")},
|
|
)
|
|
assert resp.status_code == 400
|
|
assert "earlier question" in resp.text
|
|
|
|
# Verschieben, das die Bedingung bricht, wird abgelehnt
|
|
csrf = token_for(owner, f"/forms/{pid}")
|
|
resp = owner.post(f"/forms/{pid}/questions/{q_count}/move",
|
|
data={"direction": "up", "csrf_token": csrf})
|
|
assert "problem=order_condition" in resp.headers["location"]
|
|
assert question_ids(pid)[:2] == [q_yes, q_count]
|
|
resp = owner.post(f"/forms/{pid}/order", json={"order": list(reversed(question_ids(pid)))},
|
|
headers={"X-CSRF-Token": csrf})
|
|
assert resp.status_code == 409
|
|
|
|
|
|
def test_delete_and_copy_keep_conditions_consistent(app: Any) -> None:
|
|
owner = creator(app)
|
|
pid, _, q_yes, q_count, _ = conditional_form(owner)
|
|
|
|
csrf = token_for(owner, f"/forms/{pid}")
|
|
resp = owner.post(f"/forms/{pid}/copy", data={"csrf_token": csrf})
|
|
copy_pid = resp.headers["location"].split("/")[2].split("?")[0]
|
|
copy_yes, copy_count, _, _ = question_ids(copy_pid)
|
|
assert config_of(copy_count)["condition"]["rules"][0]["q"] == copy_yes
|
|
|
|
resp = owner.post(f"/forms/{pid}/questions/{q_yes}/delete", data={"csrf_token": csrf})
|
|
assert "notice=condition_rules_removed" in resp.headers["location"]
|
|
assert "condition" not in config_of(q_count)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Gruppen beim Anlegen eines Benutzers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def admin_client(app: Any) -> TestClient:
|
|
_, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True)
|
|
assert secret
|
|
client = new_client(app)
|
|
login(client, "admin@example.de")
|
|
mfa = client.get("/login/mfa")
|
|
client.post("/login/mfa", data={"code": next_totp(secret), "csrf_token": csrf_from(mfa.text),
|
|
"next": "/"})
|
|
return client
|
|
|
|
|
|
def test_groups_suitable_for_user_type(app: Any) -> None:
|
|
client = admin_client(app)
|
|
page = client.get("/admin/groups")
|
|
client.post("/admin/groups", data={"name": "Formularteam", "roles": ["creator"],
|
|
"csrf_token": csrf_from(page.text)})
|
|
client.post("/admin/groups", data={"name": "Alle", "roles": ["admin", "creator",
|
|
"participant"],
|
|
"csrf_token": csrf_from(page.text)})
|
|
with Session(db.get_engine()) as s:
|
|
team = s.scalar(select(UserGroup).where(UserGroup.name == "Formularteam"))
|
|
everyone = s.scalar(select(UserGroup).where(UserGroup.name == "Alle"))
|
|
assert team is not None and everyone is not None
|
|
assert team.roles == ["creator"] and everyone.roles is None
|
|
team_id, all_id = str(team.public_id), str(everyone.public_id)
|
|
|
|
form = client.get("/admin/users/new")
|
|
assert 'data-roles="creator"' in form.text
|
|
resp = client.post("/admin/users/new", data={
|
|
"email": "paula@example.de", "display_name": "Paula", "role": "participant",
|
|
"groups": [team_id, all_id], "csrf_token": csrf_from(form.text)})
|
|
assert resp.status_code == 400
|
|
resp = client.post("/admin/users/new", data={
|
|
"email": "carlo@example.de", "display_name": "Carlo", "role": "creator",
|
|
"groups": [team_id, all_id], "csrf_token": csrf_from(form.text)})
|
|
assert resp.status_code == 200
|
|
with Session(db.get_engine()) as s:
|
|
user = s.scalar(select(UserAccount).where(UserAccount.email == "carlo@example.de"))
|
|
assert user is not None
|
|
groups = set(s.scalars(select(GroupMember.group_id).where(GroupMember.user_id == user.id)))
|
|
assert len(groups) == 2
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Eigene Video-Quellen
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_own_video_source_without_click(app: Any) -> None:
|
|
owner = creator(app)
|
|
_, token, q_yes, _, _ = conditional_form(owner)
|
|
with Session(db.get_engine()) as s:
|
|
media_config.save(s, media_config.MediaConfig(custom_sources=[
|
|
{"host": "nas.example.org:5001", "kind": "file", "ask": False}]))
|
|
s.commit()
|
|
pid = form_row_for_token(token)
|
|
page = f"/forms/{pid}/questions/{q_yes}"
|
|
csrf = token_for(owner, page)
|
|
resp = owner.post(f"{page}/media/embed", data={
|
|
"csrf_token": csrf, "url": "https://nas.example.org:5001/video/einweisung.mp4"})
|
|
assert "media_error" not in resp.headers["location"]
|
|
html = new_client(app).get(f"/f/{token}")
|
|
player = '<video controls preload="metadata" src="https://nas.example.org:5001/video/'
|
|
assert player in html.text
|
|
assert "media-src 'self' https://nas.example.org:5001" in html.headers[
|
|
"content-security-policy"
|
|
]
|
|
|
|
|
|
def form_row_for_token(token: str) -> str:
|
|
from surveybox.models import Form
|
|
|
|
with Session(db.get_engine()) as s:
|
|
pid = s.scalar(select(Form.public_id).where(Form.share_token == token))
|
|
return str(pid)
|