"""A2 — lottery data model and its constraints: WEB-04, ADR-10, ADR-15, ADR-22, DAT-76..79, AUD-47.""" from datetime import timedelta from uuid import uuid4 import pytest from django.contrib.auth import get_user_model from django.db import IntegrityError, connection, transaction from django.utils import timezone from apps.lottery import audit from apps.lottery.models import ( AuditEntry, AuditEntryImmutable, ChainTransaction, LotteryConfig, Movement, Participation, Round, ) pytestmark = pytest.mark.django_db PLM = 100_000_000 def make_user(name="mario"): return get_user_model().objects.create_user(name, password="x" * 12) def make_round(**kwargs): return Round.objects.create(**kwargs) def refused(make): """True if the database refuses what `make` does.""" try: with transaction.atomic(): make() except IntegrityError: return True return False # --- LotteryConfig ----------------------------------------------------------------------------- def test_config_defaults_match_the_documented_economy(): """DAT-77: bet 10 PLM, 600s rounds, 30s cooldown, 3 draw confirmations, nothing paused.""" config = LotteryConfig.get() assert config.bet_amount_sats == 10 * PLM assert (config.round_duration_seconds, config.round_cooldown_seconds, config.draw_confirmations) == (600, 30, 3) assert config.max_round_pool_sats == 0 assert not (config.pause_after_round or config.new_bets_suspended or config.withdrawals_suspended) def test_config_is_a_single_row(): LotteryConfig.get() assert LotteryConfig.objects.count() == 1 assert refused(lambda: LotteryConfig.objects.create(id=2)) @pytest.mark.parametrize( "field,value", [("bet_amount_sats", 0), ("round_duration_seconds", 0), ("max_round_pool_sats", -1), ("draw_confirmations", 0), ("draw_confirmations", 21)], ) def test_config_refuses_nonsense_values(field, value): config = LotteryConfig.get() setattr(config, field, value) assert refused(config.save) # --- Round ------------------------------------------------------------------------------------- def test_only_one_round_can_be_active(): """ADR-22: a second active round is refused whatever the code does.""" make_round(status="open") for status in ("open", "closing", "drawing", "paying_out"): assert refused(lambda s=status: make_round(status=s)) def test_any_number_of_closed_rounds_alongside_one_active(): now = timezone.now() for _ in range(3): make_round(status="closed", closed_at=now) make_round(status="open") assert Round.objects.count() == 4 def test_a_new_round_may_open_once_the_previous_is_closed(): first = make_round(status="open") first.status, first.closed_at = "closed", timezone.now() first.save() make_round(status="open") def test_a_round_keeps_its_own_rules(): """ADR-10, DAT-61: the round's parameters are its own columns, not read from the config.""" config = LotteryConfig.get() round_ = make_round(bet_amount_sats=config.bet_amount_sats, duration_seconds=600) config.bet_amount_sats = 20 * PLM config.save() round_.refresh_from_db() assert round_.bet_amount_sats == 10 * PLM @pytest.mark.parametrize( "kwargs", [ {"status": "bogus"}, {"bet_amount_sats": 0}, {"duration_seconds": 0}, {"max_round_pool_sats": -1}, {"draw_confirmations": 0}, {"status": "closed"}, # closed without a closing time {"pool_amount_sats": -1}, {"pool_amount_sats": 100, "winner_amount_sats": 80, "fee_amount_sats": 30}, # pays out more than the pool ], ) def test_round_refuses_inconsistent_rows(kwargs): assert refused(lambda: make_round(**kwargs)) def test_a_split_equal_to_the_pool_is_accepted(): make_round(status="closed", closed_at=timezone.now(), pool_amount_sats=100, winner_amount_sats=70, fee_amount_sats=30) # --- Participation ----------------------------------------------------------------------------- def test_one_bet_per_player_per_round(): """ADR-15.""" round_, user = make_round(), make_user() Participation.objects.create(round=round_, user=user, bet_amount_sats=10 * PLM) assert refused(lambda: Participation.objects.create(round=round_, user=user, bet_amount_sats=10 * PLM)) def test_the_same_player_can_bet_in_different_rounds(): user = make_user() first = make_round() Participation.objects.create(round=first, user=user, bet_amount_sats=PLM) first.status, first.closed_at = "closed", timezone.now() first.save() Participation.objects.create(round=make_round(), user=user, bet_amount_sats=PLM) def test_draw_positions_are_unique_within_a_round(): """DAT-66.""" round_ = make_round() now = timezone.now() a, b = make_user("a"), make_user("b") Participation.objects.create(round=round_, user=a, bet_amount_sats=PLM, status="confirmed", confirmed_at=now, draw_position=0) assert refused(lambda: Participation.objects.create( round=round_, user=b, bet_amount_sats=PLM, status="confirmed", confirmed_at=now, draw_position=0)) def test_unpositioned_participants_do_not_collide(): round_ = make_round() for name in ("a", "b", "c"): Participation.objects.create(round=round_, user=make_user(name), bet_amount_sats=PLM) @pytest.mark.parametrize( "kwargs", [ {"bet_amount_sats": 0}, {"status": "bogus"}, {"status": "confirmed"}, # confirmed without a confirmation time {"draw_position": 0}, # a position for a participant that is not confirmed ], ) def test_participation_refuses_inconsistent_rows(kwargs): base = {"round": make_round(), "user": make_user(), "bet_amount_sats": PLM} assert refused(lambda: Participation.objects.create(**{**base, **kwargs})) # --- Movement ---------------------------------------------------------------------------------- def test_the_sign_follows_the_kind(): """DAT-78: money in is positive, money out is negative.""" user, round_ = make_user(), make_round() now = timezone.now() Movement.objects.create(user=user, kind="deposit", amount_sats=PLM, status="confirmed", confirmed_at=now) Movement.objects.create(user=user, kind="bet", amount_sats=-PLM, round=round_) Movement.objects.create(user=user, kind="withdrawal", amount_sats=-PLM) Movement.objects.create(user=user, kind="win", amount_sats=PLM, round=round_) Movement.objects.create(user=user, kind="refund", amount_sats=PLM, round=round_) assert refused(lambda: Movement.objects.create(user=user, kind="deposit", amount_sats=-PLM)) assert refused(lambda: Movement.objects.create(user=user, kind="withdrawal", amount_sats=PLM)) assert refused(lambda: Movement.objects.create(user=user, kind="bet", amount_sats=PLM, round=round_)) @pytest.mark.parametrize( "kwargs", [ {"kind": "deposit", "amount_sats": 0}, {"kind": "bogus", "amount_sats": 1}, {"kind": "deposit", "amount_sats": 1, "status": "bogus"}, {"kind": "bet", "amount_sats": -1}, # a bet always belongs to a round {"kind": "win", "amount_sats": 1}, {"kind": "deposit", "amount_sats": 1, "status": "confirmed"}, # no confirmation time ], ) def test_movement_refuses_inconsistent_rows(kwargs): assert refused(lambda: Movement.objects.create(user=make_user(), **kwargs)) def test_the_same_request_id_is_the_same_operation(): """WEB-23, DAT-78: a repeated key from the same player cannot create a second line.""" user, other, key = make_user(), make_user("luigi"), uuid4() Movement.objects.create(user=user, kind="deposit", amount_sats=PLM, request_id=key) assert refused(lambda: Movement.objects.create(user=user, kind="deposit", amount_sats=PLM, request_id=key)) Movement.objects.create(user=other, kind="deposit", amount_sats=PLM, request_id=key) # another player: fine def test_movements_without_a_request_id_do_not_collide(): user = make_user() for _ in range(3): Movement.objects.create(user=user, kind="deposit", amount_sats=PLM) def test_amounts_are_integers_only(): """WEB-04, DAT-01: the column stores whole minimal units.""" user = make_user() movement = Movement.objects.create(user=user, kind="deposit", amount_sats=10 * PLM) movement.refresh_from_db() assert isinstance(movement.amount_sats, int) and movement.amount_sats == 1_000_000_000 # --- ChainTransaction -------------------------------------------------------------------------- def test_txids_are_unique_but_may_be_absent(): user = make_user() ChainTransaction.objects.create(kind="withdrawal", user=user) ChainTransaction.objects.create(kind="withdrawal", user=user) ChainTransaction.objects.create(kind="withdrawal", user=user, current_txid="a" * 64) assert refused(lambda: ChainTransaction.objects.create(kind="withdrawal", user=user, current_txid="a" * 64)) @pytest.mark.parametrize( "kwargs", [ {"kind": "bogus"}, {"kind": "withdrawal", "status": "bogus"}, {"kind": "withdrawal", "status": "confirmed"}, {"kind": "withdrawal", "status": "failed"}, # a failure always carries its reason {"kind": "bet"}, # a bet without a player {"kind": "payout"}, # a payout without a round ], ) def test_chain_transaction_refuses_inconsistent_rows(kwargs): user = make_user() kwargs = {"user": user, **kwargs} if kwargs["kind"] == "withdrawal" else kwargs assert refused(lambda: ChainTransaction.objects.create(**kwargs)) def test_a_failed_transaction_with_its_reason_is_accepted(): ChainTransaction.objects.create(kind="withdrawal", user=make_user(), status="failed", failed_at=timezone.now(), failure_reason="refused: inputs spent") def test_a_payout_links_to_its_round(): round_ = make_round() payout = ChainTransaction.objects.create(kind="payout", round=round_, current_txid="b" * 64) round_.payout_transaction = payout round_.save() assert Round.objects.get().payout_transaction_id == payout.pk # --- Money is never deleted -------------------------------------------------------------------- def test_rows_that_carry_money_cannot_be_deleted_with_their_owner(): """DAT-76: every foreign key is PROTECT.""" from django.db.models import ProtectedError user = make_user() Movement.objects.create(user=user, kind="deposit", amount_sats=PLM) with pytest.raises(ProtectedError): user.delete() # --- Audit ------------------------------------------------------------------------------------- def test_record_appends_a_row_with_actor_reason_and_outcome(): """AUD-47: who, when, what, why and with what outcome.""" staff = make_user("operatore") entry = audit.record("lottery_paused", actor=staff, reason="manutenzione", subject_type="config", subject_id=1, payload={"scope": "after_round"}) entry.refresh_from_db() assert (entry.actor, entry.actor_label, entry.action) == (staff, "operatore", "lottery_paused") assert (entry.reason, entry.outcome, entry.subject_id) == ("manutenzione", "ok", "1") assert entry.payload == {"scope": "after_round"} and entry.created_at <= timezone.now() def test_automatic_actions_are_attributed_to_the_system(): entry = audit.record("round_opened") assert entry.actor is None and entry.actor_label == "system" def test_the_actor_name_survives_a_rename(): staff = make_user("operatore") entry = audit.record("x", actor=staff) staff.username = "altro" staff.save() entry.refresh_from_db() assert entry.actor_label == "operatore" def test_an_audit_row_cannot_be_changed_through_the_model(): entry = audit.record("x") entry.reason = "rewritten" with pytest.raises(AuditEntryImmutable): entry.save() with pytest.raises(AuditEntryImmutable): entry.delete() with pytest.raises(AuditEntryImmutable): AuditEntry.objects.all().update(reason="rewritten") with pytest.raises(AuditEntryImmutable): AuditEntry.objects.all().delete() def test_an_audit_row_cannot_be_changed_with_raw_sql_either(): """AUD-47: the database refuses, not only the model.""" audit.record("x") from django.db import DatabaseError with connection.cursor() as cursor: with pytest.raises(DatabaseError, match="append-only"): with transaction.atomic(): cursor.execute("UPDATE lottery_auditentry SET reason = 'rewritten'") with pytest.raises(DatabaseError, match="append-only"): with transaction.atomic(): cursor.execute("DELETE FROM lottery_auditentry") assert AuditEntry.objects.count() == 1 def test_an_outcome_must_be_known(): assert refused(lambda: audit.record("x", outcome="maybe")) for outcome in ("ok", "denied", "error"): audit.record("x", outcome=outcome) def test_the_audit_is_written_in_the_same_transaction_as_the_change(): """ADR-53: if the change rolls back, so does its trace.""" with pytest.raises(RuntimeError): with transaction.atomic(): audit.record("lottery_paused") raise RuntimeError("boom") assert AuditEntry.objects.count() == 0 def test_round_timestamps_are_timezone_aware(): """DAT-02: UTC everywhere.""" round_ = make_round() assert round_.opened_at.tzinfo is not None assert abs(timezone.now() - round_.opened_at) < timedelta(seconds=5)