Gioca: the round, the player's funds and their bet; the bet is two steps (a confirmation screen that sends nothing, then an explicit confirm) with a fresh idempotency key per screen, and the server re-checks everything. Portafoglio: spendable apart from in-confirmation, deposit address with a QR of the player's own address, copy button, simulated test deposits. Movimenti: the player's own ledger, paged, stacked as cards on a phone. GET /app/stato/ feeds the page and its polling. Every view takes the user from the session only. Checked end to end in a real browser (Playwright): status moves from pending to confirmed without a reload, a double click is one bet. Mutation checks: cross-account leak, non-idempotent POST and unrestricted test-deposit amounts are all caught. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
596 lines
25 KiB
Python
596 lines
25 KiB
Python
"""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</dt><dd>10 PLM", html) and re.search(r"In conferma</dt><dd>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 "<svg" in body
|
|
other, other_user = logged_in("luigi")
|
|
assert other.get("/app/portafoglio/qr.svg").content != response.content # a different address, a different code
|
|
assert "no-store" in response["Cache-Control"] or "no-cache" in response["Cache-Control"]
|
|
|
|
|
|
def test_the_qr_takes_no_address_from_the_request():
|
|
c, user = logged_in()
|
|
plain = c.get("/app/portafoglio/qr.svg").content
|
|
assert c.get("/app/portafoglio/qr.svg?address=rplm1evil&data=evil").content == plain
|
|
|
|
|
|
# --- test deposits (WEB-26) -------------------------------------------------------------------
|
|
|
|
|
|
def test_a_test_deposit_arrives_in_confirmation_and_becomes_spendable():
|
|
c, user = logged_in(funds=0)
|
|
key = uuid4()
|
|
response = c.post("/app/portafoglio/deposito-prova/", {"amount": 50, "request_id": key})
|
|
assert response["Location"] == "/app/portafoglio/"
|
|
page = c.get("/app/portafoglio/")
|
|
assert "Deposito di prova di 50 PLM in conferma" in text(page) and "Depositi in conferma" in text(page)
|
|
assert (balance_of(user).spendable_sats, balance_of(user).incoming_sats) == (0, 50 * PLM)
|
|
simulation.settle(timezone.now() + timedelta(seconds=30))
|
|
assert (balance_of(user).spendable_sats, balance_of(user).incoming_sats) == (50 * PLM, 0)
|
|
|
|
|
|
def test_a_test_deposit_sent_twice_is_one_deposit():
|
|
c, user = logged_in(funds=0)
|
|
key = uuid4()
|
|
c.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": key})
|
|
c.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": key})
|
|
assert Movement.objects.filter(user=user, kind="deposit").count() == 1
|
|
assert "già stato registrato" in " ".join(messages_of(c.get("/app/portafoglio/")))
|
|
|
|
|
|
@pytest.mark.parametrize("amount", ["1", "1000000", "-10", "10.5", "abc", "", "9999999999999999"])
|
|
def test_only_the_offered_amounts_are_accepted(amount):
|
|
"""A tampered form gets nothing."""
|
|
c, user = logged_in(funds=0)
|
|
c.post("/app/portafoglio/deposito-prova/", {"amount": amount, "request_id": uuid4()})
|
|
assert Movement.objects.filter(user=user).count() == 0
|
|
assert "non è valida" in " ".join(messages_of(c.get("/app/portafoglio/")))
|
|
|
|
|
|
def test_test_deposits_exist_only_on_the_simulated_ledger(settings, monkeypatch):
|
|
"""WEB-26: with a real ledger the endpoint does not exist and the form is not offered."""
|
|
c, user = logged_in(funds=0)
|
|
assert "Fondi di prova" in c.get("/app/portafoglio/").content.decode()
|
|
settings.LEDGER_BACKEND = "chain"
|
|
monkeypatch.setattr("apps.web.player_views.participant_address", lambda u: "rplm1realaddress") # HD addresses: phase B
|
|
assert c.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": uuid4()}).status_code == 404
|
|
assert "Fondi di prova" not in c.get("/app/portafoglio/").content.decode()
|
|
assert Movement.objects.filter(user=user).count() == 0
|
|
|
|
|
|
def test_the_test_deposit_is_get_only_safe():
|
|
c, _ = logged_in()
|
|
assert c.get("/app/portafoglio/deposito-prova/").status_code == 405
|
|
|
|
|
|
# --- movements (WEB-25) -----------------------------------------------------------------------
|
|
|
|
|
|
def test_the_movements_are_listed_newest_first_with_sign_and_status():
|
|
round_ = open_round()
|
|
c, user = logged_in(funds=2 * BET)
|
|
post_bet(c, round_)
|
|
ledger.deposit(user, PLM, confirmed=False)
|
|
html = c.get("/app/movimenti/").content.decode()
|
|
rows = re.findall(r"<tr>(.*?)</tr>", 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"<tr>", 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"<tr>", 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"<script\b[^>]*>", 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'<a href="/app/portafoglio/" aria-current="page">Portafoglio</a>', c.get("/app/portafoglio/").content.decode())
|
|
assert re.search(r'<a href="/app/movimenti/" aria-current="page">Movimenti</a>', c.get("/app/movimenti/").content.decode())
|
|
assert "aria-current" not in c.get("/app/movimenti/").content.decode().split("Movimenti</a>")[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 "<caption" in html and html.count('scope="col"') == 5
|
|
# every cell names itself, so the stacked layout of a phone (site.css) still reads as a list of labelled facts
|
|
assert html.count('data-label="Importo"') == 1 and html.count('data-label="Stato"') == 1
|
|
css = (ROOT / "apps/web/static/web/site.css").read_text()
|
|
assert "@media (max-width: 40rem)" in css and "attr(data-label)" in css
|
|
|
|
|
|
def test_the_wallet_controls_have_labels():
|
|
c, _ = logged_in()
|
|
html = c.get("/app/portafoglio/").content.decode()
|
|
assert 'aria-label="Il tuo indirizzo di deposito"' in html and '<label for="test-amount">' 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"]
|