Files
plm-lottery/tests/django/test_home.py
T
davideandClaude Sonnet 5.5 939c113043 A6: public home with the six states, confirmed prize, countdown and polling (WEB-05, WEB-10, WEB-11, WEB-14; LIM-24, WEB-55)
public_state() feeds both the server-rendered home (works without JavaScript)
and GET /stato/, so they cannot disagree: none, open, closing, drawing, paying
and maintenance, the round's own quota, the winner's 70% of the *confirmed*
pool, bets in flight apart, and the closing time on the server's clock. home.js
counts down against the server clock and polls every 5 s while visible. Checked
in headless Chromium on mobile and desktop widths. Also records the profile
reports (WEB-55, roadmap A9) and the name-lock trade-off (LIM-24).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 14:19:56 +01:00

315 lines
13 KiB
Python

"""A6 — the public home: WEB-05, WEB-10, WEB-11, B-11, B-65, ADR-23, ADR-57."""
import json
import re
import shutil
import subprocess
from datetime import timedelta
from pathlib import Path
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.utils import timezone
from apps.lottery import lifecycle
from apps.lottery.format import plm_text
from apps.lottery.ledger import SimulatedLedger
from apps.lottery.models import LotteryConfig, Round
from apps.lottery.status import LABELS, countdown_text, public_state
ROOT = Path(__file__).resolve().parents[2]
PLM = 100_000_000
BET = 10 * PLM
pytestmark = pytest.mark.django_db
ledger = SimulatedLedger()
def make_round(status="open", **kwargs):
kwargs.setdefault("opened_at", timezone.now() - timedelta(seconds=100))
if status == "closed":
kwargs.setdefault("closed_at", timezone.now())
return Round.objects.create(status=status, **kwargs)
def bet(round_, name, *, confirm=True):
user = get_user_model().objects.create_user(name, password="x" * 12)
ledger.deposit(user, round_.bet_amount_sats)
participation = ledger.place_bet(user, round_.pk, request_id=uuid4()).obj
if confirm:
ledger.confirm_bet(participation)
return user
def set_config(**fields):
config = LotteryConfig.get()
for name, value in fields.items():
setattr(config, name, value)
config.save()
# --- the six states ----------------------------------------------------------------------------
def test_with_no_round_the_state_is_none():
state = public_state()
assert (state["state"], state["label"], state["can_participate"]) == ("none", "Nessun round in corso", False)
assert state["closes_at"] is None and state["seconds_left"] is None and state["round_id"] is None
def test_between_rounds_it_says_when_the_next_one_opens():
"""The cooldown of the round that just closed."""
now = timezone.now()
make_round("closed", closed_at=now - timedelta(seconds=10), cooldown_seconds=30)
state = public_state(now)
assert state["state"] == "none" and state["next_round_at"] is not None
assert state["next_round_at_text"] in state["message"]
assert public_state(now + timedelta(seconds=25))["next_round_at"] is None # the gap is over: about to open
def test_an_open_round_shows_quota_closing_time_and_countdown():
now = timezone.now()
round_ = make_round(opened_at=now - timedelta(seconds=100), duration_seconds=600, bet_amount_sats=7 * PLM)
state = public_state(now)
assert (state["state"], state["label"], state["can_participate"]) == ("open", "Puntate aperte", True)
assert state["seconds_left"] == 500 and state["round_id"] == round_.pk
assert state["bet_amount_text"] == "7 PLM" and state["closes_at_text"] in state["message"]
assert state["closes_at"] == (round_.opened_at + timedelta(seconds=600)).strftime("%Y-%m-%dT%H:%M:%SZ")
def test_the_quota_is_the_rounds_own_not_the_live_config():
"""ADR-10: an edit of the configuration changes nothing until the next round."""
make_round(bet_amount_sats=7 * PLM)
set_config(bet_amount_sats=99 * PLM)
assert public_state()["bet_amount_sats"] == 7 * PLM
def test_past_the_deadline_it_is_closing_even_if_the_scheduler_lags():
"""ADR-23."""
now = timezone.now()
make_round(opened_at=now - timedelta(seconds=700), duration_seconds=600) # still `open` in the database
state = public_state(now)
assert (state["state"], state["label"], state["can_participate"]) == ("closing", "In chiusura", False)
assert state["seconds_left"] is None
@pytest.mark.parametrize("status,state,label", [
("closing", "closing", "In chiusura"),
("drawing", "drawing", "Estrazione in corso"),
("paying_out", "paying", "Pagamento in attesa"),
])
def test_each_stage_after_the_betting_window(status, state, label):
shown = public_state(make_round(status) and timezone.now())
assert (shown["state"], shown["label"], shown["can_participate"]) == (state, label, False)
def test_maintenance_when_no_round_will_open():
"""ADR-57: «Pausa dopo il round in corso», once the round in progress is over."""
set_config(pause_after_round=True)
state = public_state()
assert (state["state"], state["label"], state["can_participate"]) == ("maintenance", "Manutenzione", False)
def test_a_pause_after_the_round_does_not_stop_the_round_in_progress():
"""The round still runs and is paid; the page only warns that nothing opens afterwards."""
make_round()
set_config(pause_after_round=True)
state = public_state()
assert state["state"] == "open" and state["can_participate"] and state["paused_after_round"]
assert "si ferma per manutenzione" in state["message"]
def test_suspended_bets_show_maintenance_while_the_round_runs():
"""ADR-57: «Sospendi nuove puntate» — no new bets; the bets already sent stay valid."""
make_round()
set_config(new_bets_suspended=True)
state = public_state()
assert state["state"] == "maintenance" and not state["can_participate"]
assert "già inviate restano valide" in state["message"]
assert public_state(timezone.now() + timedelta(seconds=700))["state"] == "closing" # later stages show as usual
def test_every_state_has_a_label():
assert set(LABELS) == {"none", "open", "closing", "drawing", "paying", "maintenance"}
# --- the confirmed prize -----------------------------------------------------------------------
def test_the_prize_counts_confirmed_bets_only_and_is_the_winners_share():
"""B-11, B-65: never more than will be paid; bets in flight are reported apart."""
round_ = make_round()
for name in ("a", "b", "c"):
bet(round_, name)
bet(round_, "d", confirm=False)
state = public_state()
assert state["confirmed_players"] == 3 and state["pending_players"] == 1
assert state["jackpot_sats"] == 21 * PLM and state["jackpot_text"] == "21 PLM" # 70% of 3 x 10, not of 4 x 10
def test_the_prize_ignores_a_pool_that_is_not_confirmed():
round_ = make_round()
bet(round_, "a", confirm=False)
assert public_state()["jackpot_sats"] == 0
def test_the_remainder_never_appears_in_the_prize():
round_ = make_round(bet_amount_sats=11)
bet(round_, "a")
assert public_state()["jackpot_sats"] == 7 # 70% of 11, rounded down
@pytest.mark.parametrize("sats,text", [
(0, "0 PLM"), (BET, "10 PLM"), (70_000_000, "0,7 PLM"), (1, "0,00000001 PLM"), (1_234 * PLM + 50_000_000, "1.234,5 PLM"),
(12_345_678 * PLM, "12.345.678 PLM"), (-PLM, "-1 PLM"),
])
def test_amounts_are_shown_exactly(sats, text):
assert plm_text(sats) == text
# --- the page ----------------------------------------------------------------------------------
def test_the_home_shows_the_state_without_any_script(client):
"""WEB-10: server-rendered, so it works with JavaScript off."""
round_ = make_round(bet_amount_sats=7 * PLM)
bet(round_, "a")
html = client.get("/").content.decode()
for expected in ("Puntate aperte", "7 PLM", "Montepremi confermato", "4,9 PLM", "Quota", "(ora del server)"):
assert expected in html
assert 'data-state="open"' in html and "UTC" in html
def test_participate_leads_to_the_player_area(client):
"""WEB-11."""
make_round()
html = client.get("/").content.decode()
assert re.search(r'<a class="button big" href="/app/"[^>]*>Partecipa</a>', html)
assert re.search(r'data-field="participate-line"', html) and 'hidden data-field="participate-line"' not in html
@pytest.mark.parametrize("make", [lambda: None, lambda: make_round("drawing"), lambda: set_config(pause_after_round=True)])
def test_participate_is_hidden_when_betting_is_not_possible(client, make):
make()
assert re.search(r'<p class="actions" hidden data-field="participate-line">', client.get("/").content.decode())
def test_the_player_area_sends_visitors_to_sign_in_and_back(client):
"""WEB-11: «Partecipa» then login then the play screen."""
assert client.get("/app/")["Location"] == "/accedi/?next=/app/"
def test_the_home_is_never_cached(client):
assert "no-store" in client.get("/")["Cache-Control"] or "no-cache" in client.get("/")["Cache-Control"]
def test_the_home_has_no_inline_script_and_loads_its_script_deferred(client):
html = client.get("/").content.decode()
tags = re.findall(r"<script\b[^>]*>", html)
assert tags == ['<script src="/static/web/home.js" defer>'] or all("src=" in t and "defer" in t for t in tags)
assert (ROOT / "apps/web/static/web/home.js").exists()
# --- the polling endpoint ----------------------------------------------------------------------
def test_the_state_endpoint_is_public_json_and_never_cached(client):
make_round()
response = client.get("/stato/")
assert response.status_code == 200 and response["Content-Type"].startswith("application/json")
assert "no-store" in response["Cache-Control"] or "no-cache" in response["Cache-Control"]
body = response.json()
assert set(body) >= {"state", "label", "message", "server_now", "closes_at", "seconds_left", "bet_amount_sats",
"jackpot_sats", "confirmed_players", "pending_players", "can_participate", "round_id"}
def test_the_endpoint_and_the_page_tell_the_same_story(client):
"""WEB-05: one function feeds both."""
round_ = make_round()
bet(round_, "a")
body = client.get("/stato/").json()
html = client.get("/").content.decode()
assert body["label"] in html and body["jackpot_text"] in html and body["bet_amount_text"] in html
def test_the_endpoint_exposes_no_account_data(client):
"""Only counts and amounts: no username, no address, no secret of the round."""
round_ = make_round()
bet(round_, "mariorossi")
Round.objects.filter(pk=round_.pk).update(server_seed_hash="a" * 64)
raw = client.get("/stato/").content.decode()
assert "mariorossi" not in raw and "server_seed" not in raw and "rplm1" not in raw
def test_the_countdown_follows_the_server_clock(client):
"""WEB-10: the page carries the server's time so the visitor's clock does not matter."""
make_round(opened_at=timezone.now() - timedelta(seconds=100), duration_seconds=600)
body = client.get("/stato/").json()
assert 490 <= body["seconds_left"] <= 500
assert body["server_now"].endswith("Z") and body["closes_at"].endswith("Z")
def test_the_state_follows_a_real_round_through_its_stages(settings):
"""From the worker's own steps: none -> open -> closing -> drawing -> paying -> maintenance."""
t0 = timezone.now()
assert public_state(t0)["state"] == "none"
round_ = lifecycle.open_new_round_if_needed(t0)
assert public_state(t0)["state"] == "open"
bet(round_, "a")
bet(round_, "b")
from tests.django.test_lifecycle import FakeChain
chain, end = FakeChain(1000), round_.opened_at + timedelta(seconds=round_.duration_seconds)
assert public_state(end)["state"] == "closing"
lifecycle.tick(now=end, chain=chain)
assert public_state(end)["state"] == "drawing"
chain.tip = 1003
lifecycle.tick(now=end, chain=chain)
assert public_state(end)["state"] == "paying"
set_config(pause_after_round=True)
from apps.lottery import simulation
done = end + timedelta(minutes=5)
simulation.settle(done)
lifecycle.tick(now=done, chain=chain)
assert public_state(done)["state"] == "maintenance"
# --- the script --------------------------------------------------------------------------------
NODE = shutil.which("node")
def _node(expression: str):
code = f"const m = require('{ROOT / 'apps/web/static/web/home.js'}'); console.log(JSON.stringify({expression}));"
out = subprocess.run([NODE, "-e", code], capture_output=True, text=True, check=True)
return json.loads(out.stdout)
@pytest.mark.skipif(NODE is None, reason="node is not installed")
def test_the_script_is_valid_and_its_clock_arithmetic_is_right():
subprocess.run([NODE, "--check", str(ROOT / "apps/web/static/web/home.js")], check=True)
assert _node("[m.formatCountdown(0), m.formatCountdown(59), m.formatCountdown(60), m.formatCountdown(600), "
"m.formatCountdown(3725), m.formatCountdown(-5), m.formatCountdown(61.9), m.formatCountdown(3599), "
"m.formatCountdown(3600), m.formatCountdown(7199)]") == \
["00:00", "00:59", "01:00", "10:00", "1:02:05", "00:00", "01:01", "59:59", "1:00:00", "1:59:59"]
# the visitor's clock is 10 minutes slow: the countdown still counts to the *server's* deadline
assert _node("m.secondsLeft('2026-01-01T00:10:00Z', "
"m.serverOffsetMs('2026-01-01T00:00:00Z', Date.parse('2025-12-31T23:50:00Z')), "
"Date.parse('2025-12-31T23:50:30Z'))") == 570
assert _node("[m.pollDelayMs(0), m.pollDelayMs(1), m.pollDelayMs(2), m.pollDelayMs(10)]") == [5000, 10000, 20000, 30000]
@pytest.mark.skipif(NODE is None, reason="node is not installed")
@pytest.mark.parametrize("seconds", [0, 1, 59, 60, 61, 599, 600, 3599, 3600, 3725, 7199, 86399])
def test_the_server_and_the_script_write_the_countdown_the_same_way(seconds):
"""Without JavaScript the page reads exactly as it does with it."""
assert countdown_text(seconds) == _node(f"m.formatCountdown({seconds})")
def test_the_page_renders_the_countdown_as_minutes_and_seconds(client):
make_round(opened_at=timezone.now() - timedelta(seconds=100), duration_seconds=600)
assert re.search(r'data-field="countdown">0[89]:[0-5]\d<', client.get("/").content.decode())