"""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']*>Partecipa', 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'
', 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"