feat: unlocks, inventory items, sigils, drops, and essence (Workstream C)
Implements the backend REST surface and WS wiring for
docs/superpowers/specs/2026-07-23-character-depth-ghost-log-design.md's
Workstream C:
- New models: UnlockRecord (unlocks), InventoryItem (inventory_items),
Sigil (sigils) — brand-new tables, picked up by main.py's existing
create_all.
- New app/inventory.py: unlock price table, item drop table/odds,
essence economy constants, sigil design validation, and an atomic
(row-locked) purchase_unlock() that guards against double-spend races.
- New app/routes/inventory.py: GET unlocks/items/sigils, POST sigils
(validates the placeholder {points, rune} shape, points capped at 12),
POST unlocks/{unlock_key} (402 on insufficient essence, 404 on unknown
key, idempotent re-buy).
- GET /auth/me now includes unlocks: list[str] and essence: int.
- ws.py: wires essence trickle + item_drop rolls into the one trigger
point that exists in this worktree today (_handle_summon, covering
every successful summon plus high-rarity summons); the other two
contract trigger points (correct judgment, successful ritual) belong
to Workstream B's not-yet-landed ritual/judgment WS handlers, which
should call app.inventory's same helpers once they land.
- User.essence: int added (Workstream B owns this column per the spec;
added here per orchestrator instruction so this workstream is
independently testable — merge controller reconciles the duplicate
edit).
Also fast-forwarded this worktree's branch onto master (it had fallen
behind several commits) so the files this workstream depends on
(shop.py, ws.py, entities.py, etc.) were actually present to build
against.
Tests: 109 passed (drop-roll statistical sanity with seeded RNG,
inventory/sigil CRUD, purchase success/insufficient-funds/idempotency/
unknown-key paths, /auth/me shape, ws summon-trickle and item-drop
wiring).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
352
backend/tests/test_inventory.py
Normal file
352
backend/tests/test_inventory.py
Normal file
@@ -0,0 +1,352 @@
|
||||
import random
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.inventory import (
|
||||
DROP_CHANCES,
|
||||
HIGH_RARITY_TIERS,
|
||||
ITEM_POOLS,
|
||||
SIGIL_MAX_POINTS,
|
||||
UNLOCK_PRICES,
|
||||
InsufficientEssenceError,
|
||||
UnknownUnlockError,
|
||||
credit_essence,
|
||||
purchase_unlock,
|
||||
roll_item_drop,
|
||||
summon_drop_trigger,
|
||||
validate_sigil_design,
|
||||
)
|
||||
from app.models.unlock import UnlockRecord
|
||||
from app.models.user import User
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Drop-roll probability sanity — seeded RNG, so this is a deterministic
|
||||
# statistical check, not a flaky one.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_roll_item_drop_statistical_sanity_summon_mythic():
|
||||
rng = random.Random(1234)
|
||||
trials = 20_000
|
||||
hits = sum(1 for _ in range(trials) if roll_item_drop("summon_mythic", rng) is not None)
|
||||
empirical = hits / trials
|
||||
expected = DROP_CHANCES["summon_mythic"]
|
||||
assert abs(empirical - expected) < 0.02
|
||||
|
||||
|
||||
def test_roll_item_drop_statistical_sanity_judgment():
|
||||
rng = random.Random(5678)
|
||||
trials = 20_000
|
||||
hits = sum(1 for _ in range(trials) if roll_item_drop("judgment", rng) is not None)
|
||||
empirical = hits / trials
|
||||
expected = DROP_CHANCES["judgment"]
|
||||
assert abs(empirical - expected) < 0.02
|
||||
|
||||
|
||||
def test_roll_item_drop_is_deterministic_given_same_seed():
|
||||
results_a = [roll_item_drop("ritual", random.Random(42)) for _ in range(50)]
|
||||
results_b = [roll_item_drop("ritual", random.Random(42)) for _ in range(50)]
|
||||
assert results_a == results_b
|
||||
|
||||
|
||||
def test_roll_item_drop_unknown_trigger_returns_none():
|
||||
assert roll_item_drop("not_a_real_trigger", random.Random(1)) is None
|
||||
|
||||
|
||||
def test_roll_item_drop_shape_matches_item_pool():
|
||||
# A high roll chance with a fixed seed known to hit, to check the shape.
|
||||
rng = random.Random(1234)
|
||||
item = None
|
||||
for _ in range(200):
|
||||
item = roll_item_drop("ritual", rng)
|
||||
if item is not None:
|
||||
break
|
||||
assert item is not None
|
||||
item_type, keys = ITEM_POOLS["ritual"]
|
||||
assert item["item_type"] == item_type
|
||||
assert item["item_key"] in keys
|
||||
assert item["payload"] == {"trigger": "ritual"}
|
||||
|
||||
|
||||
def test_summon_drop_trigger_only_fires_for_high_rarity():
|
||||
assert summon_drop_trigger("common") is None
|
||||
assert summon_drop_trigger("uncommon") is None
|
||||
assert summon_drop_trigger("rare") == "summon_rare"
|
||||
assert summon_drop_trigger("mythic") == "summon_mythic"
|
||||
assert HIGH_RARITY_TIERS == {"rare", "mythic"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# credit_essence
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_credit_essence_adds_and_floors_at_zero():
|
||||
user = User(username="x", password_hash="x")
|
||||
user.essence = 5
|
||||
assert credit_essence(user, 3) == 8
|
||||
assert credit_essence(user, -100) == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sigil design validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_validate_sigil_design_accepts_valid_shape():
|
||||
design = {"points": [[0, 0], [1.5, 2.5], [3, -3]], "rune": "eld"}
|
||||
normalized = validate_sigil_design(design)
|
||||
assert normalized == {"points": [[0.0, 0.0], [1.5, 2.5], [3.0, -3.0]], "rune": "eld"}
|
||||
|
||||
|
||||
def test_validate_sigil_design_rejects_too_many_points():
|
||||
design = {"points": [[i, i] for i in range(SIGIL_MAX_POINTS + 1)], "rune": "eld"}
|
||||
assert validate_sigil_design(design) is None
|
||||
|
||||
|
||||
def test_validate_sigil_design_accepts_max_points():
|
||||
design = {"points": [[i, i] for i in range(SIGIL_MAX_POINTS)], "rune": "eld"}
|
||||
assert validate_sigil_design(design) is not None
|
||||
|
||||
|
||||
def test_validate_sigil_design_rejects_empty_points():
|
||||
assert validate_sigil_design({"points": [], "rune": "eld"}) is None
|
||||
|
||||
|
||||
def test_validate_sigil_design_rejects_bad_point_shape():
|
||||
assert validate_sigil_design({"points": [[1, 2, 3]], "rune": "eld"}) is None
|
||||
assert validate_sigil_design({"points": [["a", "b"]], "rune": "eld"}) is None
|
||||
assert validate_sigil_design({"points": "not-a-list", "rune": "eld"}) is None
|
||||
|
||||
|
||||
def test_validate_sigil_design_rejects_missing_or_bad_rune():
|
||||
assert validate_sigil_design({"points": [[0, 0]]}) is None
|
||||
assert validate_sigil_design({"points": [[0, 0]], "rune": ""}) is None
|
||||
assert validate_sigil_design({"points": [[0, 0]], "rune": 5}) is None
|
||||
assert validate_sigil_design({"points": [[0, 0]], "rune": "x" * 33}) is None
|
||||
|
||||
|
||||
def test_validate_sigil_design_rejects_non_dict():
|
||||
assert validate_sigil_design("nope") is None
|
||||
assert validate_sigil_design(None) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# purchase_unlock — success, insufficient funds, unknown unlock, idempotency,
|
||||
# race safety.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_purchase_unlock_success_deducts_essence_and_records(db_session):
|
||||
user = User(username="buyer", password_hash="x", essence=100)
|
||||
db_session.add(user)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(user)
|
||||
|
||||
price = UNLOCK_PRICES["listening_tool"]
|
||||
record = await purchase_unlock(db_session, user.id, "listening_tool")
|
||||
assert record.unlock_key == "listening_tool"
|
||||
|
||||
await db_session.refresh(user)
|
||||
assert user.essence == 100 - price
|
||||
|
||||
rows = (
|
||||
await db_session.execute(
|
||||
select(UnlockRecord).where(UnlockRecord.user_id == user.id)
|
||||
)
|
||||
).scalars().all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].unlock_key == "listening_tool"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_purchase_unlock_insufficient_funds_raises_and_does_not_charge(db_session):
|
||||
user = User(username="pauper", password_hash="x", essence=5)
|
||||
db_session.add(user)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(user)
|
||||
|
||||
with pytest.raises(InsufficientEssenceError):
|
||||
await purchase_unlock(db_session, user.id, "listening_tool")
|
||||
|
||||
await db_session.refresh(user)
|
||||
assert user.essence == 5
|
||||
rows = (
|
||||
await db_session.execute(
|
||||
select(UnlockRecord).where(UnlockRecord.user_id == user.id)
|
||||
)
|
||||
).scalars().all()
|
||||
assert rows == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_purchase_unlock_unknown_key_raises(db_session):
|
||||
user = User(username="curious", password_hash="x", essence=1000)
|
||||
db_session.add(user)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(user)
|
||||
|
||||
with pytest.raises(UnknownUnlockError):
|
||||
await purchase_unlock(db_session, user.id, "does_not_exist")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_purchase_unlock_is_idempotent_does_not_double_charge(db_session):
|
||||
user = User(username="rebuyer", password_hash="x", essence=100)
|
||||
db_session.add(user)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(user)
|
||||
|
||||
price = UNLOCK_PRICES["listening_tool"]
|
||||
await purchase_unlock(db_session, user.id, "listening_tool")
|
||||
await db_session.refresh(user)
|
||||
assert user.essence == 100 - price
|
||||
|
||||
# Buying again must not charge a second time.
|
||||
await purchase_unlock(db_session, user.id, "listening_tool")
|
||||
await db_session.refresh(user)
|
||||
assert user.essence == 100 - price
|
||||
|
||||
rows = (
|
||||
await db_session.execute(
|
||||
select(UnlockRecord).where(UnlockRecord.user_id == user.id)
|
||||
)
|
||||
).scalars().all()
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP layer: purchase endpoint, list endpoints, sigil save, /auth/me shape.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _register_and_login(client, username="seeker"):
|
||||
await client.post(
|
||||
"/auth/register", json={"username": username, "password": "spookyspooky"}
|
||||
)
|
||||
resp = await client.post(
|
||||
"/auth/login", json={"username": username, "password": "spookyspooky"}
|
||||
)
|
||||
return resp.json()["id"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_buy_unlock_success_over_http(client, db_session):
|
||||
user_id = await _register_and_login(client, "affluent")
|
||||
user = await db_session.get(User, uuid.UUID(user_id))
|
||||
user.essence = 100
|
||||
await db_session.commit()
|
||||
|
||||
resp = await client.post("/api/inventory/unlocks/listening_tool")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["unlock_key"] == "listening_tool"
|
||||
assert body["essence"] == 100 - UNLOCK_PRICES["listening_tool"]
|
||||
|
||||
me = await client.get("/auth/me")
|
||||
assert me.json()["unlocks"] == ["listening_tool"]
|
||||
assert me.json()["essence"] == 100 - UNLOCK_PRICES["listening_tool"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_buy_unlock_insufficient_funds_over_http(client, db_session):
|
||||
await _register_and_login(client, "broke")
|
||||
# A fresh user starts with 0 essence.
|
||||
resp = await client.post("/api/inventory/unlocks/listening_tool")
|
||||
assert resp.status_code == 402
|
||||
|
||||
me = await client.get("/auth/me")
|
||||
assert me.json()["unlocks"] == []
|
||||
assert me.json()["essence"] == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_buy_unlock_unknown_key_over_http(client):
|
||||
await _register_and_login(client, "explorer")
|
||||
resp = await client.post("/api/inventory/unlocks/nonexistent_thing")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_buy_unlock_requires_auth(client):
|
||||
resp = await client.post("/api/inventory/unlocks/listening_tool")
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inventory_list_endpoints_require_auth(client):
|
||||
assert (await client.get("/api/inventory/unlocks")).status_code == 401
|
||||
assert (await client.get("/api/inventory/items")).status_code == 401
|
||||
assert (await client.get("/api/inventory/sigils")).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_unlocks_and_items_empty_then_populated(client, db_session):
|
||||
user_id = await _register_and_login(client, "collector")
|
||||
|
||||
empty = await client.get("/api/inventory/unlocks")
|
||||
assert empty.status_code == 200
|
||||
assert empty.json() == []
|
||||
|
||||
user = await db_session.get(User, uuid.UUID(user_id))
|
||||
user.essence = 100
|
||||
await db_session.commit()
|
||||
await client.post("/api/inventory/unlocks/listening_tool")
|
||||
|
||||
populated = await client.get("/api/inventory/unlocks")
|
||||
assert len(populated.json()) == 1
|
||||
assert populated.json()[0]["unlock_key"] == "listening_tool"
|
||||
assert "unlocked_at" in populated.json()[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_and_list_sigil(client):
|
||||
await _register_and_login(client, "sigilsmith")
|
||||
|
||||
resp = await client.post(
|
||||
"/api/inventory/sigils",
|
||||
json={"name": "ward-of-quiet", "design": {"points": [[0, 0], [1, 1]], "rune": "eld"}},
|
||||
)
|
||||
assert resp.status_code == 201
|
||||
body = resp.json()
|
||||
assert body["name"] == "ward-of-quiet"
|
||||
assert body["design"]["rune"] == "eld"
|
||||
|
||||
listed = await client.get("/api/inventory/sigils")
|
||||
assert len(listed.json()) == 1
|
||||
assert listed.json()[0]["name"] == "ward-of-quiet"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_sigil_rejects_too_many_points(client):
|
||||
await _register_and_login(client, "greedy-sigilsmith")
|
||||
resp = await client.post(
|
||||
"/api/inventory/sigils",
|
||||
json={
|
||||
"name": "overreach",
|
||||
"design": {"points": [[i, i] for i in range(13)], "rune": "eld"},
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_sigil_rejects_missing_rune(client):
|
||||
await _register_and_login(client, "runeless")
|
||||
resp = await client.post(
|
||||
"/api/inventory/sigils",
|
||||
json={"name": "blank", "design": {"points": [[0, 0]]}},
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auth_me_includes_essence_and_unlocks_default(client):
|
||||
await _register_and_login(client, "freshuser")
|
||||
resp = await client.get("/auth/me")
|
||||
body = resp.json()
|
||||
assert body["essence"] == 0
|
||||
assert body["unlocks"] == []
|
||||
@@ -1,12 +1,16 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
|
||||
import app.ws
|
||||
from app.entities import fallback_profile
|
||||
from app.inventory import SUMMON_ESSENCE_TRICKLE
|
||||
from app.models.contact_session import ContactSession
|
||||
from app.models.event import Event
|
||||
from app.models.inventory_item import InventoryItem
|
||||
from app.models.user import User
|
||||
from app.rate_limit import RateLimiter
|
||||
|
||||
|
||||
@@ -266,3 +270,168 @@ async def test_summon_per_ip_bucket_follows_cf_connecting_ip_not_socket_peer(
|
||||
# A different visitor IP behind the same tunnel — must not be
|
||||
# rejected by visitor A's already-spent bucket.
|
||||
_read_until(ws, "entity")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_summon_credits_essence_trickle(sync_client, db_session, monkeypatch):
|
||||
# The module-level summon_ip_limiter/summon_limiter are shared singletons
|
||||
# that persist real hit counts across every test in this file (they're
|
||||
# only overridden where a test explicitly monkeypatches them, as earlier
|
||||
# tests above do) — fresh, generous instances here keep this test from
|
||||
# depending on how many summons ran before it.
|
||||
monkeypatch.setattr(app.ws, "summon_ip_limiter", RateLimiter(max_requests=1000, window_seconds=60))
|
||||
monkeypatch.setattr(app.ws, "summon_limiter", RateLimiter(max_requests=1000, window_seconds=60))
|
||||
|
||||
token = _login(sync_client, "trickle-earner")
|
||||
user_id = uuid.UUID(
|
||||
sync_client.get("/auth/me", headers={"cookie": f"qm_session={token}"}).json()["id"]
|
||||
)
|
||||
|
||||
with _ws_connect(sync_client, token) as ws:
|
||||
_read_until(ws, "session")
|
||||
ws.send_json({"type": "summon"})
|
||||
_read_until(ws, "entity")
|
||||
_read_until(ws, "utterance", kind="greeting")
|
||||
|
||||
for _ in range(40):
|
||||
db_session.expire_all()
|
||||
user = await db_session.get(User, user_id)
|
||||
if user.essence == SUMMON_ESSENCE_TRICKLE:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
assert user.essence == SUMMON_ESSENCE_TRICKLE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_summon_high_rarity_item_drop_is_persisted_and_sent(
|
||||
sync_client, db_session, monkeypatch
|
||||
):
|
||||
# Force a hit so the wiring is exercised deterministically rather than
|
||||
# relying on the real roll odds (those are covered statistically in
|
||||
# test_inventory.py).
|
||||
forced_item = {
|
||||
"item_type": "curio",
|
||||
"item_key": "veil_thread",
|
||||
"payload": {"trigger": "summon_mythic"},
|
||||
}
|
||||
monkeypatch.setattr(app.ws, "roll_item_drop", lambda trigger: forced_item)
|
||||
# See test_summon_credits_essence_trickle above re: why this is reset.
|
||||
monkeypatch.setattr(app.ws, "summon_ip_limiter", RateLimiter(max_requests=1000, window_seconds=60))
|
||||
monkeypatch.setattr(app.ws, "summon_limiter", RateLimiter(max_requests=1000, window_seconds=60))
|
||||
|
||||
class MythicSpiritService:
|
||||
async def mint_profile(self, signature, channel, anomalies, language="en"):
|
||||
profile = fallback_profile(signature)
|
||||
profile["rarity"] = "mythic"
|
||||
return profile
|
||||
|
||||
async def fragment(self, source, anomaly, language="en"):
|
||||
return "listen"
|
||||
|
||||
async def wire_whisper(self, telemetry, language="en"):
|
||||
return "the wire hums"
|
||||
|
||||
def chat_stream(self, entity, question, history, language="en"):
|
||||
async def gen():
|
||||
yield "hi"
|
||||
|
||||
return gen()
|
||||
|
||||
def ambient_ready(self):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(app.ws, "spirit_service", MythicSpiritService())
|
||||
|
||||
token = _login(sync_client, "jackpot-seeker")
|
||||
user_id = uuid.UUID(
|
||||
sync_client.get("/auth/me", headers={"cookie": f"qm_session={token}"}).json()["id"]
|
||||
)
|
||||
|
||||
with _ws_connect(sync_client, token) as ws:
|
||||
_read_until(ws, "session")
|
||||
ws.send_json({"type": "summon"})
|
||||
entity_frame = _read_until(ws, "entity")
|
||||
assert entity_frame["entity"]["rarity"] == "mythic"
|
||||
drop_frame = _read_until(ws, "item_drop")
|
||||
assert drop_frame["item"] == forced_item
|
||||
|
||||
for _ in range(40):
|
||||
db_session.expire_all()
|
||||
items = (
|
||||
await db_session.execute(
|
||||
select(InventoryItem).where(InventoryItem.user_id == user_id)
|
||||
)
|
||||
).scalars().all()
|
||||
if items:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(items) == 1
|
||||
assert items[0].item_key == "veil_thread"
|
||||
assert items[0].item_type == "curio"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_summon_common_rarity_does_not_roll_a_drop(sync_client, db_session, monkeypatch):
|
||||
# See test_summon_credits_essence_trickle above re: why this is reset.
|
||||
monkeypatch.setattr(app.ws, "summon_ip_limiter", RateLimiter(max_requests=1000, window_seconds=60))
|
||||
monkeypatch.setattr(app.ws, "summon_limiter", RateLimiter(max_requests=1000, window_seconds=60))
|
||||
|
||||
# Common is the overwhelmingly likely fallback rarity (55% weight) but
|
||||
# not guaranteed — force it explicitly so this test can't flake.
|
||||
def _common_only(signature: str) -> dict:
|
||||
profile = fallback_profile(signature)
|
||||
profile["rarity"] = "common"
|
||||
return profile
|
||||
|
||||
class CommonSpiritService:
|
||||
async def mint_profile(self, signature, channel, anomalies, language="en"):
|
||||
return _common_only(signature)
|
||||
|
||||
async def fragment(self, source, anomaly, language="en"):
|
||||
return "listen"
|
||||
|
||||
async def wire_whisper(self, telemetry, language="en"):
|
||||
return "the wire hums"
|
||||
|
||||
def chat_stream(self, entity, question, history, language="en"):
|
||||
async def gen():
|
||||
yield "hi"
|
||||
|
||||
return gen()
|
||||
|
||||
def ambient_ready(self):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(app.ws, "spirit_service", CommonSpiritService())
|
||||
# If a drop were (incorrectly) rolled for a common-rarity summon, this
|
||||
# would make it always hit — proving the rarity gate, not just the odds,
|
||||
# is what's preventing a drop here.
|
||||
monkeypatch.setattr(
|
||||
app.ws, "roll_item_drop", lambda trigger: {"item_type": "x", "item_key": "y", "payload": {}}
|
||||
)
|
||||
|
||||
token = _login(sync_client, "commoner")
|
||||
user_id = uuid.UUID(
|
||||
sync_client.get("/auth/me", headers={"cookie": f"qm_session={token}"}).json()["id"]
|
||||
)
|
||||
|
||||
with _ws_connect(sync_client, token) as ws:
|
||||
_read_until(ws, "session")
|
||||
ws.send_json({"type": "summon"})
|
||||
entity_frame = _read_until(ws, "entity")
|
||||
assert entity_frame["entity"]["rarity"] == "common"
|
||||
greeting = _read_until(ws, "utterance", kind="greeting")
|
||||
assert greeting["kind"] == "greeting"
|
||||
|
||||
# Give the (already-awaited, so this should be immediate) reward path a
|
||||
# moment to land, then assert no item was ever persisted for this user —
|
||||
# the rarity gate, not just the roll odds, is what prevents a drop here.
|
||||
for _ in range(20):
|
||||
db_session.expire_all()
|
||||
items = (
|
||||
await db_session.execute(
|
||||
select(InventoryItem).where(InventoryItem.user_id == user_id)
|
||||
)
|
||||
).scalars().all()
|
||||
await asyncio.sleep(0.02)
|
||||
assert items == []
|
||||
|
||||
Reference in New Issue
Block a user