Files
plm-lottery/tests/django/test_console.py
T

294 lines
12 KiB
Python

"""A9 — operations console, pauses, admin and reports: WEB-30, WEB-31, WEB-32, WEB-40, WEB-41, WEB-42, WEB-43,
WEB-44, WEB-55, ADR-57."""
from datetime import timedelta
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.management import call_command
from django.test import Client
from django.utils import timezone
from apps.lottery import console, lifecycle
from apps.lottery.errors import LedgerError
from apps.lottery.ledger import get_ledger
from apps.lottery.models import AuditEntry, LotteryConfig, Movement, Report
User = get_user_model()
PASSWORD = "correct-horse-battery"
pytestmark = pytest.mark.django_db
ALL = ["view_console", "pause_after_round", "suspend_new_bets", "suspend_withdrawals"]
def player(name="mario"):
return User.objects.create_user(name, password=PASSWORD)
def staff(name="ops", perms=tuple(ALL)):
user = User.objects.create_user(name, password=PASSWORD, is_staff=True)
user.user_permissions.set(Permission.objects.filter(codename__in=perms, content_type__app_label="lottery"))
return user
def client_for(user):
client = Client()
client.force_login(user)
return client
def post(client, url, data):
return client.post(url, data)
def run(client, key, *, enable="1", reason="incident 42", confirm="1"):
return post(client, f"/ops/{key}/", {"enable": enable, "reason": reason, "confirm": confirm})
# --- who may enter (WEB-30) -----------------------------------------------------------------
def test_anonymous_visitors_are_sent_to_sign_in(client):
response = client.get("/ops/")
assert response.status_code == 302 and response["Location"].startswith("/accedi/")
def test_a_player_cannot_open_the_console(client):
assert client_for(player()).get("/ops/").status_code == 403
def test_staff_without_the_permission_cannot_open_the_console():
assert client_for(staff(perms=())).get("/ops/").status_code == 403
def test_staff_with_the_permission_sees_the_console():
html = client_for(staff()).get("/ops/").content.decode()
assert "Console operativa" in html and "Pausa dopo il round in corso" in html
def test_a_command_without_the_csrf_token_is_refused():
client = Client(enforce_csrf_checks=True)
client.force_login(staff())
response = client.post("/ops/sospendi-puntate/", {"enable": "1", "reason": "no token", "confirm": "1"})
assert response.status_code == 403 and not LotteryConfig.get().new_bets_suspended
# --- the three commands (WEB-40, WEB-41, WEB-42, WEB-44) ---------------------------------------
@pytest.mark.parametrize("key,field,on,off", [
("pausa-dopo-round", "pause_after_round", "pause_after_round_enabled", "pause_after_round_disabled"),
("sospendi-puntate", "new_bets_suspended", "new_bets_suspended", "new_bets_resumed"),
("sospendi-prelievi", "withdrawals_suspended", "withdrawals_suspended", "withdrawals_resumed"),
])
def test_each_command_switches_only_its_own_flag_and_is_audited(key, field, on, off):
user = staff()
client = client_for(user)
assert run(client, key, reason="planned maintenance").status_code == 302
config = LotteryConfig.get()
flags = {f: getattr(config, f) for f in ("pause_after_round", "new_bets_suspended", "withdrawals_suspended")}
assert flags == {f: f == field for f in flags}
entry = AuditEntry.objects.get(action=on)
assert (entry.actor, entry.reason, entry.outcome) == (user, "planned maintenance", "ok")
assert run(client, key, enable="0", reason="all clear").status_code == 302
assert not getattr(LotteryConfig.get(), field)
assert AuditEntry.objects.get(action=off).reason == "all clear"
@pytest.mark.parametrize("key", ["pausa-dopo-round", "sospendi-puntate", "sospendi-prelievi"])
def test_a_player_cannot_run_a_command_and_the_refusal_is_audited(key):
assert run(client_for(player()), key).status_code == 403
config = LotteryConfig.get()
assert not (config.pause_after_round or config.new_bets_suspended or config.withdrawals_suspended)
assert AuditEntry.objects.filter(outcome="denied", actor__username="mario").count() == 1
def test_a_permission_for_one_command_does_not_open_the_others():
client = client_for(staff(perms=("view_console", "suspend_new_bets")))
assert run(client, "sospendi-prelievi").status_code == 403
assert not LotteryConfig.get().withdrawals_suspended
assert run(client, "sospendi-puntate").status_code == 302
assert LotteryConfig.get().new_bets_suspended
def test_the_service_itself_refuses_without_the_permission():
"""The view is not the only gate: the service checks again (WEB-44)."""
with pytest.raises(Exception) as caught:
console.run_command(staff(perms=("view_console",)), console.COMMANDS["sospendi-puntate"], True, "because")
assert caught.type.__name__ == "PermissionDenied"
assert not LotteryConfig.get().new_bets_suspended
def test_a_command_needs_a_reason_and_a_confirmation():
client = client_for(staff())
assert "motivo" in run(client, "sospendi-puntate", reason=" ").content.decode()
assert "Conferma" in run(client, "sospendi-puntate", confirm="").content.decode()
assert not LotteryConfig.get().new_bets_suspended
assert not AuditEntry.objects.filter(action="new_bets_suspended").exists()
def test_repeating_a_command_changes_nothing_and_adds_no_audit_row():
client = client_for(staff())
run(client, "sospendi-puntate")
run(client, "sospendi-puntate") # a double submit
assert LotteryConfig.get().new_bets_suspended
assert AuditEntry.objects.filter(action="new_bets_suspended").count() == 1
def test_the_command_page_says_what_continues_and_what_to_check_before_resuming():
client = client_for(staff())
assert "Cosa continua" in client.get("/ops/sospendi-puntate/").content.decode()
run(client, "sospendi-puntate")
html = client.get("/ops/sospendi-puntate/").content.decode()
assert "Riprendi le puntate" in html and "Verifiche prima della ripresa" in html
# --- the site reflects the pause (WEB-44) -----------------------------------------------------
def test_suspending_bets_shows_maintenance_on_the_site_and_refuses_a_bet(client):
round_ = lifecycle.open_new_round_if_needed()
user = player()
ledger = get_ledger()
ledger.deposit(user, round_.bet_amount_sats * 2)
run(client_for(staff()), "sospendi-puntate")
state = client.get("/stato/").json()
assert state["state"] == "maintenance" and not state["can_participate"]
with pytest.raises(LedgerError) as refused:
ledger.place_bet(user, round_.pk, request_id=uuid4())
assert refused.value.code == "bets_suspended"
def test_pausing_after_the_round_stops_the_next_one_from_opening():
run(client_for(staff()), "pausa-dopo-round")
assert lifecycle.open_new_round_if_needed() is None
# --- what the console shows (WEB-31) -----------------------------------------------------------
def test_the_worker_tick_leaves_a_heartbeat():
assert not console.console_state()["worker_alive"]
call_command("run_worker", "--once")
assert console.console_state()["worker_alive"]
def test_a_silent_worker_is_reported_as_stopped():
console.beat(timezone.now() - timedelta(minutes=5))
html = client_for(staff()).get("/ops/").content.decode()
assert "fermo" in html
def test_operations_pending_for_too_long_are_listed():
user = player()
old = timezone.now() - console.LATE_AFTER - timedelta(minutes=1)
Movement.objects.create(user=user, kind="deposit", status="pending", amount_sats=5, created_at=old)
assert console.console_state()["late"]["pending_movements"] == 1
assert console.console_state()["late_total"] == 1
def test_the_pause_reason_is_shown_while_it_lasts():
client = client_for(staff())
run(client, "sospendi-puntate", reason="node unreachable")
assert "node unreachable" in client.get("/ops/").content.decode()
# --- reports (WEB-55) -------------------------------------------------------------------------
def test_a_player_sends_a_report_and_sees_its_status():
user = player()
client = client_for(user)
assert post(client, "/app/profilo/segnalazioni/", {"text": "The bet button is stuck"}).status_code == 302
report = Report.objects.get()
assert (report.user, report.status) == (user, "open")
assert AuditEntry.objects.filter(action="report_submitted", subject_id=str(report.pk)).exists()
html = client.get("/app/profilo/").content.decode()
assert "The bet button is stuck" in html and "Aperta" in html
def test_a_player_sees_only_their_own_reports():
Report.objects.create(user=player("luigi"), text="luigi's secret problem")
assert "luigi's secret problem" not in client_for(player()).get("/app/profilo/").content.decode()
def test_a_report_must_have_text_of_a_sane_length_and_a_refusal_does_not_use_the_quota():
client = client_for(player())
assert post(client, "/app/profilo/segnalazioni/", {"text": ""}).status_code == 400
assert post(client, "/app/profilo/segnalazioni/", {"text": "x" * 1001}).status_code == 400
assert not Report.objects.exists()
for number in range(10): # the ten refusals above would have used it up if they counted
assert post(client, "/app/profilo/segnalazioni/", {"text": f"problem number {number}"}).status_code == 302
def test_reports_are_limited_per_user():
client = client_for(player())
for number in range(10):
post(client, "/app/profilo/segnalazioni/", {"text": f"problem number {number}"})
response = post(client, "/app/profilo/segnalazioni/", {"text": "one problem too many"})
assert response.status_code == 429 and "Retry-After" in response
assert Report.objects.count() == 10
assert post(client_for(player("luigi")), "/app/profilo/segnalazioni/", {"text": "another player is fine"}).status_code == 302
def test_sending_a_report_needs_a_session(client):
assert client.post("/app/profilo/segnalazioni/", {"text": "anonymous"}).status_code in (302, 403)
assert not Report.objects.exists()
# --- admin (WEB-32) ---------------------------------------------------------------------------
def admin_user():
return User.objects.create_superuser("boss", password=PASSWORD)
def test_changing_a_report_status_in_the_admin_is_audited():
boss = admin_user()
report = Report.objects.create(user=player(), text="please look")
client = client_for(boss)
response = client.post(f"/admin/lottery/report/{report.pk}/change/", {"status": "resolved"})
assert response.status_code == 302
report.refresh_from_db()
assert report.status == "resolved" and report.status_changed_at is not None
entry = AuditEntry.objects.get(action="report_status_changed")
assert (entry.actor, entry.payload) == (boss, {"from": "open", "to": "resolved"})
def test_the_text_of_a_report_cannot_be_edited_in_the_admin():
report = Report.objects.create(user=player(), text="original")
client_for(admin_user()).post(f"/admin/lottery/report/{report.pk}/change/", {"status": "read", "text": "tampered"})
report.refresh_from_db()
assert (report.text, report.status) == ("original", "read")
@pytest.mark.parametrize("model", ["round", "movement", "chaintransaction", "auditentry", "participation"])
def test_game_records_are_read_only_in_the_admin(model):
client = client_for(admin_user())
assert client.get(f"/admin/lottery/{model}/").status_code == 200
assert client.get(f"/admin/lottery/{model}/add/").status_code == 403
def test_a_user_page_shows_game_records_and_cannot_delete_the_user():
user = player()
client = client_for(admin_user())
html = client.get(f"/admin/accounts/user/{user.pk}/change/").content.decode()
assert "Movements (read-only)" in html
assert client.post(f"/admin/accounts/user/{user.pk}/delete/", {"post": "yes"}).status_code == 403
def test_deactivating_a_user_in_the_admin_is_audited():
user = player()
client = client_for(admin_user())
data = {"username": user.username, "date_joined_0": "2026-01-01", "date_joined_1": "00:00:00", "is_staff": "",
"password": user.password, # is_active left out: unchecked
"participations-TOTAL_FORMS": "0", "participations-INITIAL_FORMS": "0",
"movements-TOTAL_FORMS": "0", "movements-INITIAL_FORMS": "0"}
client.post(f"/admin/accounts/user/{user.pk}/change/", data)
user.refresh_from_db()
assert not user.is_active
assert AuditEntry.objects.get(action="user_changed").payload == {"is_active": False}