"""A7 — the player area: WEB-03, WEB-05, WEB-20..WEB-27, BET-07, ADR-34, ADR-35.""" import html as htmllib 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.test import Client from django.utils import timezone from apps.lottery import lifecycle, simulation from apps.lottery.addresses import participant_address from apps.lottery.balances import balance_of from apps.lottery.ledger import SimulatedLedger from apps.lottery.models import AuditEntry, LotteryConfig, Movement, Participation, Round ROOT = Path(__file__).resolve().parents[2] User = get_user_model() PLM = 100_000_000 BET = 10 * PLM PASSWORD = "correct-horse-battery" pytestmark = pytest.mark.django_db ledger = SimulatedLedger() PLAYER_URLS = ["/app/", "/app/stato/", "/app/punta/", "/app/portafoglio/", "/app/portafoglio/qr.svg", "/app/movimenti/"] def make_user(name="mario", funds=BET): user = User.objects.create_user(name, password=PASSWORD) if funds: ledger.deposit(user, funds) return user def logged_in(name="mario", funds=BET): user = make_user(name, funds) client = Client() client.force_login(user) return client, user def open_round(**kwargs): kwargs.setdefault("opened_at", timezone.now() - timedelta(seconds=60)) return Round.objects.create(**kwargs) def post_bet(client, round_, request_id=None): return client.post("/app/punta/", {"round_id": round_.pk, "request_id": request_id or uuid4()}) def text(response): """The visible text of a page: tags removed, entities decoded, whitespace collapsed.""" return re.sub(r"\s+", " ", htmllib.unescape(re.sub(r"<[^>]+>", " ", response.content.decode()))) def messages_of(response): return re.findall(r'class="message [^"]*">([^<]+)<', response.content.decode()) # --- access: only a signed-in player, only their own data (WEB-03) ---------------------------- @pytest.mark.parametrize("url", PLAYER_URLS) def test_every_player_page_needs_a_session(client, url): response = client.get(url) assert response.status_code == 302 and response["Location"].startswith("/accedi/?next=") def test_posting_without_a_session_is_refused(client): assert client.post("/app/punta/", {"round_id": 1, "request_id": uuid4()})["Location"].startswith("/accedi/") assert client.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": uuid4()})["Location"].startswith("/accedi/") def test_the_forms_need_the_csrf_token(): user = make_user() open_round() csrf = Client(enforce_csrf_checks=True) csrf.force_login(user) assert csrf.post("/app/punta/", {"round_id": 1, "request_id": uuid4()}).status_code == 403 assert csrf.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": uuid4()}).status_code == 403 assert Participation.objects.count() == 0 and Movement.objects.filter(kind="deposit").count() == 1 def test_a_player_never_sees_another_players_data(): """WEB-03: balances, bets, movements and the QR are always the signed-in player's own.""" round_ = open_round() mario, luigi = Client(), Client() a, b = make_user("mario"), make_user("luigi", funds=3 * BET) mario.force_login(a) luigi.force_login(b) assert post_bet(luigi, round_).status_code == 302 state = mario.get("/app/stato/").json()["me"] assert state["participation"] is None and state["spendable_sats"] == BET # not luigi's 2 x BET, not his bet assert "luigi" not in text(mario.get("/app/movimenti/")) and "luigi" not in text(mario.get("/app/")) assert "Non ci sono ancora movimenti" not in text(mario.get("/app/movimenti/")) # mario has his own deposit assert "Puntata" not in text(mario.get("/app/movimenti/")) # luigi's bet is not in mario's history assert "Puntata" in text(luigi.get("/app/movimenti/")) assert participant_address(a) != participant_address(b) assert participant_address(b) not in mario.get("/app/portafoglio/").content.decode() def test_user_ids_in_the_request_are_ignored(): """No view takes a user from the request: a forged parameter changes nothing.""" client, mario = logged_in("mario") other = make_user("luigi", funds=5 * BET) forged = f"?user={other.pk}&user_id={other.pk}" assert client.get("/app/stato/" + forged).json()["me"]["spendable_sats"] == BET assert "luigi" not in text(client.get("/app/movimenti/" + forged)) and "50 PLM" not in text(client.get("/app/movimenti/" + forged)) assert participant_address(other) not in client.get("/app/portafoglio/" + forged).content.decode() # --- the play screen (WEB-20) ----------------------------------------------------------------- def test_the_play_screen_shows_the_round_the_funds_and_the_bet_button(client): open_round() c, _ = logged_in() page = text(c.get("/app/")) assert "Puntate aperte" in page and "Saldo spendibile" in page and "10 PLM" in page and "Punta 10 PLM" in page assert 'href="/app/punta/"' in c.get("/app/").content.decode() def test_the_bet_button_is_hidden_without_funds_and_says_why(): open_round() c, _ = logged_in(funds=0) html = c.get("/app/").content.decode() assert re.search(r'data-me="bet-form" hidden', html) assert "servono 10 PLM spendibili" in text(c.get("/app/")) def test_funds_still_in_confirmation_ask_to_wait(): """BET-07, ADR-34: the balance on screen is not the balance that can be spent.""" open_round() user = make_user(funds=0) ledger.deposit(user, BET, confirmed=False) c = Client() c.force_login(user) page = text(c.get("/app/")) assert "ancora in conferma" in page and "In conferma" in page assert not c.get("/app/stato/").json()["me"]["can_bet"] def test_the_play_screen_says_so_when_betting_is_closed(): open_round(status="drawing") c, _ = logged_in() me = c.get("/app/stato/").json()["me"] assert not me["can_bet"] and "Il vincitore sarà scelto" in me["bet_blocker"] # --- placing a bet: two steps, explicit confirmation (WEB-22) --------------------------------- def test_the_confirmation_screen_shows_round_amount_and_funds_and_sends_nothing(): round_ = open_round() c, user = logged_in() response = c.get("/app/punta/") page = text(response) assert response.status_code == 200 assert re.search(rf"Round {round_.pk} Importo 10 PLM", page) assert "10 PLM" in page and "Conferma e punta" in page and "Saldo spendibile" in page assert Participation.objects.count() == 0 and balance_of(user).spendable_sats == BET # looking costs nothing def test_opening_the_confirmation_does_not_place_the_bet_by_itself(): open_round() c, user = logged_in() for _ in range(3): c.get("/app/punta/") assert Participation.objects.count() == 0 def test_confirming_places_the_bet_and_shows_its_real_state(): """WEB-22: after sending, the page says what actually happened — here, waiting for confirmation.""" round_ = open_round() c, user = logged_in() response = post_bet(c, round_) assert response.status_code == 302 and response["Location"] == "/app/" page = c.get("/app/") assert "Puntata inviata" in text(page) and "In attesa di conferma" in text(page) assert re.search(r'data-me="bet-form" hidden', page.content.decode()) bet = Participation.objects.get() assert (bet.user, bet.round, bet.status, bet.bet_amount_sats) == (user, round_, "pending", BET) assert balance_of(user).spendable_sats == 0 def test_a_page_reload_recovers_the_saved_state(): """WEB-22: the state lives on the server; reloading (or coming back) shows the same thing.""" round_ = open_round() c, _ = logged_in() post_bet(c, round_) first = text(c.get("/app/")) second = text(c.get("/app/")) assert "In attesa di conferma" in first and "In attesa di conferma" in second fresh = Client() fresh.force_login(User.objects.get()) # a new browser, same player assert "In attesa di conferma" in text(fresh.get("/app/")) def test_the_status_follows_the_bet_to_confirmation(): round_ = open_round() c, _ = logged_in() post_bet(c, round_) simulation.settle(timezone.now() + timedelta(seconds=30)) page = text(c.get("/app/")) assert "Confermata" in page and "Partecipi all'estrazione" in page assert c.get("/app/stato/").json()["me"]["participation"]["status"] == "confirmed" def test_a_rejected_bet_says_so_and_the_funds_are_back(): round_ = open_round() c, user = logged_in() post_bet(c, round_) ledger.reject_bet(Participation.objects.get(), "refused") page = text(c.get("/app/")) assert "Rifiutata" in page and "i fondi sono tornati disponibili" in page assert balance_of(user).spendable_sats == BET def test_an_excluded_bet_says_so_and_is_refunded(): round_ = open_round() c, user = logged_in() post_bet(c, round_) bet = Participation.objects.get() ledger.confirm_bet(bet) ledger.exclude_bet(bet, "gone from the chain") page = text(c.get("/app/")) assert "Esclusa dall'estrazione" in page and "rimborsato" in page assert balance_of(user).spendable_sats == BET # --- the double send (WEB-23) ------------------------------------------------------------------ def test_sending_the_same_confirmation_twice_makes_one_bet(): round_ = open_round() c, user = logged_in(funds=3 * BET) key = uuid4() first, second = post_bet(c, round_, key), post_bet(c, round_, key) assert first.status_code == second.status_code == 302 assert Participation.objects.count() == 1 and Movement.objects.filter(kind="bet").count() == 1 assert balance_of(user).spendable_sats == 2 * BET # charged once assert "già stata registrata" in " ".join(messages_of(c.get("/app/"))) def test_the_same_confirmation_opened_in_two_tabs_makes_one_bet(): """Two tabs, two keys: the second is refused as «already betting», nothing is charged twice.""" round_ = open_round() c, user = logged_in(funds=3 * BET) post_bet(c, round_) again = post_bet(c, round_) assert again["Location"] == "/app/" assert "Hai già una puntata" in text(c.get("/app/")) assert Participation.objects.count() == 1 and balance_of(user).spendable_sats == 2 * BET def test_each_confirmation_screen_carries_its_own_fresh_key(): open_round() c, _ = logged_in() keys = {re.search(r'name="request_id" value="([^"]+)"', c.get("/app/punta/").content.decode()).group(1) for _ in range(3)} assert len(keys) == 3 # --- the server decides (WEB-22) -------------------------------------------------------------- @pytest.mark.parametrize("prepare,expected", [ (lambda r: Round.objects.filter(pk=r.pk).update(status="closing"), "chiuse"), (lambda r: Round.objects.filter(pk=r.pk).update(opened_at=timezone.now() - timedelta(seconds=700)), "chiuse"), (lambda r: setattr(LotteryConfig.get(), "new_bets_suspended", True) or LotteryConfig.objects.update(new_bets_suspended=True), "sospese"), ]) def test_a_stale_confirmation_is_refused_by_the_server_with_a_clear_message(prepare, expected): """The page was open while the round changed: the server checks everything again.""" round_ = open_round() c, user = logged_in() prepare(round_) response = post_bet(c, round_) assert response["Location"] == "/app/" assert expected in " ".join(messages_of(c.get("/app/"))) assert Participation.objects.count() == 0 and balance_of(user).spendable_sats == BET def test_a_bet_without_enough_funds_is_refused(): round_ = open_round() c, _ = logged_in(funds=BET - 1) post_bet(c, round_) assert "Saldo insufficiente: servono 10 PLM" in " ".join(messages_of(c.get("/app/"))) assert Participation.objects.count() == 0 @pytest.mark.parametrize("data", [ {"round_id": "abc", "request_id": "not-a-uuid"}, {"round_id": "", "request_id": ""}, {"request_id": "x"}, {}, ]) def test_a_malformed_request_is_refused_politely(data): open_round() c, user = logged_in() response = c.post("/app/punta/", data) assert response.status_code == 302 and Participation.objects.count() == 0 assert balance_of(user).spendable_sats == BET def test_the_confirmation_screen_redirects_when_betting_is_not_possible(): open_round(status="drawing") c, _ = logged_in() assert c.get("/app/punta/")["Location"] == "/app/" assert "Il vincitore sarà scelto" in " ".join(messages_of(c.get("/app/"))) def test_a_player_with_a_bet_cannot_open_a_second_confirmation(): round_ = open_round() c, _ = logged_in(funds=2 * BET) post_bet(c, round_) assert c.get("/app/punta/")["Location"] == "/app/" assert "Hai già una puntata" in " ".join(messages_of(c.get("/app/"))) # --- polling (WEB-05, WEB-27) ----------------------------------------------------------------- def test_the_player_state_adds_the_players_block_to_the_public_one(): open_round() c, _ = logged_in() body = c.get("/app/stato/").json() assert body["state"] == "open" and set(body["me"]) >= { "spendable_sats", "spendable_text", "incoming_sats", "incoming_text", "participation", "can_bet", "bet_blocker", "last_result"} assert "no-store" in c.get("/app/stato/")["Cache-Control"] or "no-cache" in c.get("/app/stato/")["Cache-Control"] def test_the_page_and_the_endpoint_tell_the_same_story(): round_ = open_round() c, _ = logged_in() post_bet(c, round_) body, page = c.get("/app/stato/").json(), text(c.get("/app/")) assert body["me"]["participation"]["label"] in page and body["me"]["spendable_text"] in page def test_the_play_page_polls_the_players_endpoint(): open_round() c, _ = logged_in() html = c.get("/app/").content.decode() assert 'data-poll-url="/app/stato/"' in html and "home.js" in html # --- how a round ends for the player ---------------------------------------------------------- def test_the_player_is_told_how_their_round_ended(): """The winner reads «hai vinto», the others «non hai vinto»; the round then belongs to the past.""" t0 = timezone.now() round_ = lifecycle.open_new_round_if_needed(t0) clients = {} for name in ("a", "b", "c"): c, _ = logged_in(name) post_bet(c, round_) clients[name] = c for bet in Participation.objects.all(): ledger.confirm_bet(bet) from tests.django.test_lifecycle import FakeChain chain, end = FakeChain(1000), round_.opened_at + timedelta(seconds=round_.duration_seconds) lifecycle.tick(now=end, chain=chain) chain.tip = 1003 lifecycle.tick(now=end, chain=chain) done = end + timedelta(minutes=5) simulation.settle(done) lifecycle.tick(now=done, chain=chain) round_.refresh_from_db() winner = round_.winner.username for name, c in clients.items(): line = c.get("/app/stato/").json()["me"]["last_result"] if name == winner: assert line == f"Round {round_.pk}: hai vinto 21 PLM." # 70% of 3 x 10 else: assert line == f"Round {round_.pk}: non hai vinto questa volta." # --- the wallet (WEB-21) ---------------------------------------------------------------------- def test_the_wallet_separates_spendable_funds_from_funds_in_confirmation(): user = make_user(funds=BET) ledger.deposit(user, 5 * PLM, confirmed=False) c = Client() c.force_login(user) html = c.get("/app/portafoglio/").content.decode() page = text(c.get("/app/portafoglio/")) assert re.search(r"Spendibile
10 PLM", html) and re.search(r"In conferma
5 PLM", html) assert "Depositi in conferma" in page and "5 PLM" in page def test_the_wallet_shows_network_address_qr_and_a_copy_control(): c, user = logged_in() html = c.get("/app/portafoglio/").content.decode() assert "PLM regtest" in html and participant_address(user) in html assert 'src="/app/portafoglio/qr.svg"' in html and 'alt="QR code' in html assert 'data-copy-target="deposit-address"' in html and "readonly" in html # still copyable without JavaScript assert "wallet.js" in html def test_the_qr_is_an_svg_of_the_players_own_address(): c, user = logged_in() response = c.get("/app/portafoglio/qr.svg") body = response.content.decode() assert response.status_code == 200 and response["Content-Type"] == "image/svg+xml" and "(.*?)", html, re.S)[1:] # without the header row assert len(rows) == 3 assert "Deposito" in rows[0] and "In conferma" in rows[0] and "+1 PLM" in rows[0] # the newest assert "Puntata" in rows[1] and "-10 PLM" in rows[1] and "round" in rows[1] assert "Deposito" in rows[2] and "Confermato" in rows[2] and "+20 PLM" in rows[2] def test_a_transaction_shows_its_txid_and_says_when_it_is_simulated(): round_ = open_round() c, user = logged_in() post_bet(c, round_) txid = Participation.objects.get().bet_txid html = c.get("/app/movimenti/").content.decode() assert f'title="{txid}"' in html and f"{txid[:10]}…{txid[-6:]}" in html and "(simulata)" in html def test_the_txid_links_to_the_explorer_when_one_is_configured(settings): settings.EXPLORER_TX_URL = "https://explorer.example/tx/{txid}" round_ = open_round() c, user = logged_in() post_bet(c, round_) txid = Participation.objects.get().bet_txid assert f'href="https://explorer.example/tx/{txid}"' in c.get("/app/movimenti/").content.decode() def test_movements_are_paged(): c, user = logged_in(funds=0) for _ in range(30): ledger.deposit(user, PLM) first = c.get("/app/movimenti/") assert len(re.findall(r"", first.content.decode())) == 1 + 25 # header row + 25 assert "Pagina 1 di 2" in text(first) and "Meno recenti" in text(first) second = c.get("/app/movimenti/?pagina=2") assert len(re.findall(r"", second.content.decode())) == 1 + 5 and "Più recenti" in text(second) assert c.get("/app/movimenti/?pagina=999").status_code == 200 # a page out of range is the last one, not an error def test_an_empty_history_points_to_the_wallet(): c, _ = logged_in(funds=0) assert "Non ci sono ancora movimenti" in text(c.get("/app/movimenti/")) # --- markup, accessibility, scripts ----------------------------------------------------------- @pytest.mark.parametrize("url", ["/app/", "/app/punta/", "/app/portafoglio/", "/app/movimenti/"]) def test_player_pages_use_no_inline_scripts_or_styles(url): open_round() c, _ = logged_in() html = c.get(url, follow=True).content.decode() inline = [m for m in re.findall(r"]*>", html) if "src=" not in m] assert not inline and " style=" not in html and not re.search(r"\son[a-z]+=", html) def test_the_current_section_is_marked_in_the_navigation(): c, _ = logged_in() assert re.search(r'Portafoglio', c.get("/app/portafoglio/").content.decode()) assert re.search(r'Movimenti', c.get("/app/movimenti/").content.decode()) assert "aria-current" not in c.get("/app/movimenti/").content.decode().split("Movimenti")[0].split("Portafoglio")[0] def test_the_movements_table_is_accessible_and_stacks_on_a_phone(): c, user = logged_in() html = c.get("/app/movimenti/").content.decode() assert "' in html NODE = shutil.which("node") @pytest.mark.skipif(NODE is None, reason="node is not installed") def test_the_wallet_script_is_valid_and_copies_through_the_clipboard_api(): script = ROOT / "apps/web/static/web/wallet.js" subprocess.run([NODE, "--check", str(script)], check=True) code = f""" const {{ copyText }} = require('{script}'); (async () => {{ const copied = []; await copyText('rplm1abc', {{ writeText: async (t) => copied.push(t) }}); let refused = false; try {{ await copyText('x', undefined); }} catch (e) {{ refused = true; }} console.log(JSON.stringify({{ copied, refused }})); }})(); """ out = subprocess.run([NODE, "-e", code], capture_output=True, text=True, check=True) assert json.loads(out.stdout) == {"copied": ["rplm1abc"], "refused": True} def test_every_ledger_error_has_an_italian_text(): from apps.lottery.messages import ledger_error_text for code in ("no_round_open", "round_closing", "already_betting", "bets_suspended", "missing_request_id", "idempotency_conflict", "invalid_amount", "round_full"): assert ledger_error_text(code, {}) and not re.search(r"[a-z]+_[a-z]+", ledger_error_text(code, {})) assert "10 PLM" in ledger_error_text("insufficient_balance", {"required_sats": BET}) assert "5 PLM" in ledger_error_text("balance_pending_confirmation", {"pending_sats": 5 * PLM}) assert ledger_error_text("something_new", {}) def test_the_audit_records_what_the_player_did(): round_ = open_round() c, user = logged_in() post_bet(c, round_) actions = list(AuditEntry.objects.order_by("id").values_list("action", flat=True)) assert actions == ["deposit_credited", "bet_placed"]