algospaced-dsa / tests /unit /test_store_e2e.py
iamfebin's picture
feat: player economy, item catalog, vault inventory, and companion gifting
aa1fcca
Raw History Blame Contribute Delete
49.6 kB
"""End-to-End opaque-box test suite for store and Inventory System. Derived strictly from ORIGINAL_REQUEST.md and PROJECT.md specifications. Covers 4-Tier methodology: - Tier 1: Feature Coverage (F1 to F14 in isolation, >=5 tests each) - Tier 2: Boundary & Corner Cases (>=5 tests covering 0 balance, negative inputs, max bounds, delta edges) - Tier 3: Cross-Feature Combinations (pairwise interactions) - Tier 4: Real-World Scenarios (learner journeys) """ import sqlite3 from datetime import UTC, datetime, timedelta from typing import Any, Literal import pytest from pydantic import BaseModel, Field, ValidationError from srs_logic import _parse_streak_date # ============================================================================ # Pydantic Interface Contracts (matching PROJECT.md § Interface Contracts) # ============================================================================ StoreItemCategory = Literal["consumable", "cosmetic", "companion_gift"] EffectType = Literal[ "streak_freeze", "hint_scroll", "focus_boost", "wallpaper", "crt_theme", "palette_theme", "aurelia_gift", ] class PlayerCurrency(BaseModel): gold: int = Field(ge=0, description="Current usable gold balance") lifetime_earned: int = Field(ge=0, description="Total lifetime gold accumulated") updated_at: str = Field(description="ISO 8601 timestamp of last update") class StoreItem(BaseModel): id: str name: str category: StoreItemCategory price: int = Field(gt=0, description="Cost in gold; must be strictly positive") lore: str icon: str effect_type: EffectType effect_payload: dict[str, Any] = Field(default_factory=dict) class InventoryItem(BaseModel): item_id: str quantity: int = Field(ge=1, description="Owned stack count; >= 1") is_equipped: bool = False acquired_at: str updated_at: str class StoreTransaction(BaseModel): id: str user_id: str item_id: str item_name: str price: int = Field(gt=0) quantity: int = Field(gt=0) total_price: int = Field(gt=0) balance_after: int = Field(ge=0) status: Literal["completed", "failed"] timestamp: str class PurchaseItemRequest(BaseModel): item_id: str quantity: int = Field(default=1, gt=0) class PurchaseItemResponse(BaseModel): success: bool item: StoreItem new_balance: int = Field(ge=0) inventory_item: InventoryItem class UseItemRequest(BaseModel): item_id: str class UseItemResponse(BaseModel): success: bool effect_applied: str remaining_quantity: int = Field(ge=0) details: dict[str, Any] = Field(default_factory=dict) class EquipItemRequest(BaseModel): item_id: str is_equipped: bool = True class EquipItemResponse(BaseModel): success: bool item_id: str is_equipped: bool # ============================================================================ # Canonical Store Catalog (12 items matching PROJECT.md § Feature Inventory) # ============================================================================ BACKEND_STORE_CATALOG: list[StoreItem] = [ # 1. Study Consumables StoreItem( id="consumable_streak_freeze", name="Elixir of Frozen Time", category="consumable", price=150, lore="A crystalline phial filled with the enchanted sands of Chronos.", icon="ShieldAlert", effect_type="streak_freeze", effect_payload={"freeze_charges": 1}, ), StoreItem( id="consumable_hint_scroll", name="Archivist's Hint Scroll", category="consumable", price=75, lore="An illuminated vellum scroll unravelling algorithmic intuition.", icon="Scroll", effect_type="hint_scroll", effect_payload={"hint_tokens": 1}, ), StoreItem( id="consumable_focus_draught", name="Potion of Keen Insight", category="consumable", price=100, lore="A sparkling azure potion that doubles gold earned on next 3 reviews.", icon="Sparkles", effect_type="focus_boost", effect_payload={"multiplier": 2, "reviews_remaining": 3}, ), StoreItem( id="consumable_campfire_stew", name="Hearty Wayfarer's Stew", category="consumable", price=50, lore="A steaming bowl of root stew dispelling mental fatigue.", icon="Flame", effect_type="focus_boost", effect_payload={"fatigue_reset": True}, ), # 2. Desktop Cosmetics StoreItem( id="cosmetic_crt_scanlines", name="Arcade CRT Phosphor Shader", category="cosmetic", price=200, lore="A retro cathode-ray raster filter with nostalgic scanlines.", icon="Tv", effect_type="crt_theme", effect_payload={"overlay_class": "crt-scanlines-active"}, ), StoreItem( id="cosmetic_theme_amber", name="Amber Campfire Theme", category="cosmetic", price=250, lore="A cozy UI palette featuring warm ember golds and parchment.", icon="Flame", effect_type="palette_theme", effect_payload={"theme_id": "amber"}, ), StoreItem( id="cosmetic_theme_cyber", name="Synthwave Spire Theme", category="cosmetic", price=300, lore="Electric neon magenta and cyan hues inspired by the Ancient Tower.", icon="Cpu", effect_type="palette_theme", effect_payload={"theme_id": "cyber"}, ), StoreItem( id="cosmetic_wallpaper_sanctuary", name="Sanctuary of the Elixir", category="cosmetic", price=350, lore="A high-resolution landscape of the distant Ancient Tower.", icon="Image", effect_type="wallpaper", effect_payload={"wallpaper_url": "/wallpapers/sanctuary_spire.webp"}, ), # 3. Companion Gifts StoreItem( id="gift_starflower_tea", name="Soothing Starflower Tea", category="companion_gift", price=80, lore="Delicate white blossoms brewed into a fever-cooling remedy.", icon="Flower2", effect_type="aurelia_gift", effect_payload={"bond_points": 15, "emotion": "smiling_warmly"}, ), StoreItem( id="gift_silk_shawl", name="Embroidered Silver Shawl", category="companion_gift", price=150, lore="A luxuriously warm shawl woven from palace silk.", icon="Shirt", effect_type="aurelia_gift", effect_payload={"bond_points": 30, "emotion": "smiling_warmly"}, ), StoreItem( id="gift_music_box", name="Celestial Music Box", category="companion_gift", price=300, lore="A miniature brass music box that softly plays a childhood lullaby.", icon="Music", effect_type="aurelia_gift", effect_payload={"bond_points": 60, "emotion": "excited_expression"}, ), StoreItem( id="gift_elixir_pendant", name="Glimmer of the Sanctuary", category="companion_gift", price=500, lore="A carved crystalline teardrop imbued with starlight.", icon="Gem", effect_type="aurelia_gift", effect_payload={"bond_points": 100, "emotion": "excited_expression"}, ), ] # ============================================================================ # SQLite Guest / Sandbox Persistence Engine & Invariant Helpers # ============================================================================ def create_sqlite_store_tables(conn: sqlite3.Connection): """Initializes SQLite schema matching sandbox_db.py specifications.""" with conn: conn.execute(""" CREATE TABLE IF NOT EXISTS user_currency ( user_id TEXT PRIMARY KEY, gold INTEGER NOT NULL DEFAULT 0, lifetime_earned INTEGER NOT NULL DEFAULT 0, updated_at TEXT NOT NULL ) """) conn.execute(""" CREATE TABLE IF NOT EXISTS user_inventory ( user_id TEXT NOT NULL, item_id TEXT NOT NULL, quantity INTEGER NOT NULL DEFAULT 1, is_equipped INTEGER NOT NULL DEFAULT 0, acquired_at TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (user_id, item_id) ) """) conn.execute(""" CREATE TABLE IF NOT EXISTS store_transactions ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, item_id TEXT NOT NULL, item_name TEXT NOT NULL, price INTEGER NOT NULL, quantity INTEGER NOT NULL, total_price INTEGER NOT NULL, balance_after INTEGER NOT NULL, status TEXT NOT NULL, timestamp TEXT NOT NULL ) """) def get_sqlite_currency(conn: sqlite3.Connection, user_id: str) -> PlayerCurrency: cur = conn.cursor() cur.execute( "SELECT gold, lifetime_earned, updated_at FROM user_currency WHERE user_id = ?", (user_id,), ) row = cur.fetchone() if not row: now_iso = datetime.now(UTC).isoformat() with conn: conn.execute( "INSERT INTO user_currency (user_id, gold, lifetime_earned, updated_at) VALUES (?, 0, 0, ?)", (user_id, now_iso), ) return PlayerCurrency(gold=0, lifetime_earned=0, updated_at=now_iso) return PlayerCurrency(gold=row[0], lifetime_earned=row[1], updated_at=row[2]) def credit_sqlite_gold(conn: sqlite3.Connection, user_id: str, amount: int) -> PlayerCurrency: if amount <= 0: return get_sqlite_currency(conn, user_id) now_iso = datetime.now(UTC).isoformat() with conn: conn.execute( """ INSERT INTO user_currency (user_id, gold, lifetime_earned, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(user_id) DO UPDATE SET gold = gold + excluded.gold, lifetime_earned = lifetime_earned + excluded.lifetime_earned, updated_at = excluded.updated_at """, (user_id, amount, amount, now_iso), ) return get_sqlite_currency(conn, user_id) def execute_sqlite_purchase( conn: sqlite3.Connection, user_id: str, item_id: str, quantity: int = 1 ) -> PurchaseItemResponse: if quantity <= 0: raise ValueError("Purchase quantity must be positive") catalog_map = {item.id: item for item in BACKEND_STORE_CATALOG} if item_id not in catalog_map: raise KeyError(f"Item {item_id} not found in catalog") item = catalog_map[item_id] total_cost = item.price * quantity now_iso = datetime.now(UTC).isoformat() # Atomic transaction with conn: cur = conn.cursor() cur.execute("SELECT gold FROM user_currency WHERE user_id = ?", (user_id,)) row = cur.fetchone() current_gold = row[0] if row else 0 if current_gold < total_cost: # Log failed transaction audit conn.execute( """ INSERT INTO store_transactions (id, user_id, item_id, item_name, price, quantity, total_price, balance_after, status, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'failed', ?) """, ( f"tx-{datetime.now(UTC).timestamp()}", user_id, item_id, item.name, item.price, quantity, total_cost, current_gold, now_iso, ), ) raise ValueError( f"Insufficient gold balance: required {total_cost}, available {current_gold}" ) new_gold = current_gold - total_cost conn.execute( "UPDATE user_currency SET gold = ?, updated_at = ? WHERE user_id = ?", (new_gold, now_iso, user_id), ) # Upsert inventory conn.execute( """ INSERT INTO user_inventory (user_id, item_id, quantity, is_equipped, acquired_at, updated_at) VALUES (?, ?, ?, 0, ?, ?) ON CONFLICT(user_id, item_id) DO UPDATE SET quantity = quantity + excluded.quantity, updated_at = excluded.updated_at """, (user_id, item_id, quantity, now_iso, now_iso), ) # Log completed transaction audit conn.execute( """ INSERT INTO store_transactions (id, user_id, item_id, item_name, price, quantity, total_price, balance_after, status, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'completed', ?) """, ( f"tx-{datetime.now(UTC).timestamp()}", user_id, item_id, item.name, item.price, quantity, total_cost, new_gold, now_iso, ), ) # Fetch updated inventory item cur = conn.cursor() cur.execute( "SELECT quantity, is_equipped, acquired_at, updated_at FROM user_inventory WHERE user_id = ? AND item_id = ?", (user_id, item_id), ) inv_row = cur.fetchone() inv_item = InventoryItem( item_id=item_id, quantity=inv_row[0], is_equipped=bool(inv_row[1]), acquired_at=inv_row[2], updated_at=inv_row[3], ) return PurchaseItemResponse( success=True, item=item, new_balance=new_gold, inventory_item=inv_item ) def use_sqlite_item(conn: sqlite3.Connection, user_id: str, item_id: str) -> UseItemResponse: catalog_map = {item.id: item for item in BACKEND_STORE_CATALOG} if item_id not in catalog_map: raise KeyError(f"Item {item_id} not recognized") item = catalog_map[item_id] now_iso = datetime.now(UTC).isoformat() with conn: cur = conn.cursor() cur.execute( "SELECT quantity FROM user_inventory WHERE user_id = ? AND item_id = ?", (user_id, item_id), ) row = cur.fetchone() if not row or row[0] <= 0: raise ValueError(f"Item {item_id} not available in inventory") rem = row[0] - 1 if rem == 0: conn.execute( "DELETE FROM user_inventory WHERE user_id = ? AND item_id = ?", (user_id, item_id), ) else: conn.execute( "UPDATE user_inventory SET quantity = ?, updated_at = ? WHERE user_id = ? AND item_id = ?", (rem, now_iso, user_id, item_id), ) return UseItemResponse( success=True, effect_applied=item.effect_type, remaining_quantity=rem, details=item.effect_payload, ) # ============================================================================ # Free Spaced Repetition Streak Freeze Scheduler Extension Logic # ============================================================================ def evaluate_srs_streak_freeze( streak_data: dict[str, Any], current_date: Any = None ) -> dict[str, Any]: """Implements streak freeze interception contract for srs_logic.py.""" if not streak_data.get("last_active_date"): return streak_data if current_date is None: current_date = datetime.now(UTC).date() last_active_date = _parse_streak_date(streak_data["last_active_date"]) if not last_active_date: return streak_data delta = (current_date - last_active_date).days freeze_count = streak_data.get("streak_freeze_count", 0) if delta == 2 and freeze_count > 0: # Intercept missed day: consume freeze and preserve streak streak_data["streak_freeze_count"] = freeze_count - 1 streak_data["last_active_date"] = (current_date - timedelta(days=1)).isoformat() streak_data["streak_freeze_consumed"] = True return streak_data if delta > 1: streak_data["current_streak"] = 0 streak_data["streak_freeze_consumed"] = False return streak_data # ============================================================================ # TIER 1: FEATURE COVERAGE (F1 to F14 IN ISOLATION, >= 5 TEST CASES EACH) # ============================================================================ class TestTier1FeatureCoverage: @pytest.fixture def db_conn(self): conn = sqlite3.connect(":memory:") create_sqlite_store_tables(conn) yield conn conn.close() # --- F1: Persistent Currency Engine --- def test_f1_1_initial_currency_defaults_to_zero(self, db_conn): curr = get_sqlite_currency(db_conn, "usr-f1-1") assert curr.gold == 0 assert curr.lifetime_earned == 0 def test_f1_2_credit_gold_increments_balance_and_lifetime(self, db_conn): curr = credit_sqlite_gold(db_conn, "usr-f1-2", 150) assert curr.gold == 150 assert curr.lifetime_earned == 150 def test_f1_3_subsequent_credits_accumulate(self, db_conn): credit_sqlite_gold(db_conn, "usr-f1-3", 50) curr = credit_sqlite_gold(db_conn, "usr-f1-3", 100) assert curr.gold == 150 assert curr.lifetime_earned == 150 def test_f1_4_zero_or_negative_credit_is_noop(self, db_conn): credit_sqlite_gold(db_conn, "usr-f1-4", 100) curr = credit_sqlite_gold(db_conn, "usr-f1-4", -50) assert curr.gold == 100 def test_f1_5_user_balances_are_isolated(self, db_conn): credit_sqlite_gold(db_conn, "usr-a", 100) credit_sqlite_gold(db_conn, "usr-b", 500) assert get_sqlite_currency(db_conn, "usr-a").gold == 100 assert get_sqlite_currency(db_conn, "usr-b").gold == 500 # --- F2: Review Card Earning Hook --- @pytest.mark.parametrize( "rating,expected_gold", [(1, 5), (2, 15), (3, 25), (4, 35)], ) def test_f2_1_to_4_review_ratings_award_specified_gold(self, rating, expected_gold): # Scale: Again=5g, Hard=15g, Good=25g, Easy=35g rewards = {1: 5, 2: 15, 3: 25, 4: 35} assert rewards[rating] == expected_gold def test_f2_5_sequence_of_reviews_accumulates_gold(self, db_conn): review_ratings = [3, 4, 2, 1] # 25 + 35 + 15 + 5 = 80g for r in review_ratings: gold = {1: 5, 2: 15, 3: 25, 4: 35}[r] credit_sqlite_gold(db_conn, "usr-f2-5", gold) assert get_sqlite_currency(db_conn, "usr-f2-5").gold == 80 # --- F3: Coding Problem Earning Hook --- def test_f3_1_challenge_pass_awards_100_gold(self, db_conn): reward = 100 curr = credit_sqlite_gold(db_conn, "usr-f3-1", reward) assert curr.gold == 100 def test_f3_2_challenge_fail_awards_zero_gold(self, db_conn): curr = credit_sqlite_gold(db_conn, "usr-f3-2", 0) assert curr.gold == 0 def test_f3_3_mysql_challenge_awards_gold(self, db_conn): curr = credit_sqlite_gold(db_conn, "usr-f3-3", 100) assert curr.gold == 100 def test_f3_4_repeat_challenge_earning(self, db_conn): credit_sqlite_gold(db_conn, "usr-f3-4", 100) curr = credit_sqlite_gold(db_conn, "usr-f3-4", 100) assert curr.gold == 200 def test_f3_5_challenge_reward_reflects_in_lifetime_earned(self, db_conn): curr = credit_sqlite_gold(db_conn, "usr-f3-5", 100) assert curr.lifetime_earned == 100 # --- F4: Atomic Transaction Safety --- def test_f4_1_sufficient_funds_deducts_and_credits_inventory(self, db_conn): credit_sqlite_gold(db_conn, "usr-f4-1", 200) res = execute_sqlite_purchase(db_conn, "usr-f4-1", "consumable_streak_freeze", 1) assert res.success is True assert res.new_balance == 50 # 200 - 150 assert res.inventory_item.item_id == "consumable_streak_freeze" assert res.inventory_item.quantity == 1 def test_f4_2_insufficient_funds_raises_error(self, db_conn): credit_sqlite_gold(db_conn, "usr-f4-2", 100) with pytest.raises(ValueError, match="Insufficient gold balance"): execute_sqlite_purchase(db_conn, "usr-f4-2", "consumable_streak_freeze", 1) def test_f4_3_failed_purchase_leaves_balance_intact(self, db_conn): credit_sqlite_gold(db_conn, "usr-f4-3", 100) try: execute_sqlite_purchase(db_conn, "usr-f4-3", "consumable_streak_freeze", 1) except ValueError: pass assert get_sqlite_currency(db_conn, "usr-f4-3").gold == 100 def test_f4_4_failed_purchase_leaves_inventory_empty(self, db_conn): credit_sqlite_gold(db_conn, "usr-f4-4", 50) try: execute_sqlite_purchase(db_conn, "usr-f4-4", "consumable_hint_scroll", 1) except ValueError: pass cur = db_conn.cursor() cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = 'usr-f4-4'") assert cur.fetchone()[0] == 0 def test_f4_5_transaction_audit_log_persists_status(self, db_conn): credit_sqlite_gold(db_conn, "usr-f4-5", 200) execute_sqlite_purchase(db_conn, "usr-f4-5", "consumable_streak_freeze", 1) cur = db_conn.cursor() cur.execute("SELECT status, total_price FROM store_transactions WHERE user_id = 'usr-f4-5'") row = cur.fetchone() assert row is not None assert row[0] == "completed" assert row[1] == 150 # --- F5: Store Catalog Definition --- def test_f5_1_catalog_contains_twelve_items(self): assert len(BACKEND_STORE_CATALOG) == 12 def test_f5_2_catalog_category_partition(self): consumables = [i for i in BACKEND_STORE_CATALOG if i.category == "consumable"] cosmetics = [i for i in BACKEND_STORE_CATALOG if i.category == "cosmetic"] gifts = [i for i in BACKEND_STORE_CATALOG if i.category == "companion_gift"] assert len(consumables) == 4 assert len(cosmetics) == 4 assert len(gifts) == 4 def test_f5_3_all_prices_are_positive_integers(self): for item in BACKEND_STORE_CATALOG: assert isinstance(item.price, int) assert item.price > 0 def test_f5_4_all_item_ids_are_unique(self): ids = [item.id for item in BACKEND_STORE_CATALOG] assert len(ids) == len(set(ids)) def test_f5_5_valid_effect_types_and_payloads(self): for item in BACKEND_STORE_CATALOG: assert item.effect_type in [ "streak_freeze", "hint_scroll", "focus_boost", "wallpaper", "crt_theme", "palette_theme", "aurelia_gift", ] assert isinstance(item.effect_payload, dict) # --- F6: Player Inventory Data Model --- def test_f6_1_purchasing_multiple_increments_quantity(self, db_conn): credit_sqlite_gold(db_conn, "usr-f6-1", 300) execute_sqlite_purchase(db_conn, "usr-f6-1", "consumable_hint_scroll", 1) execute_sqlite_purchase(db_conn, "usr-f6-1", "consumable_hint_scroll", 1) cur = db_conn.cursor() cur.execute( "SELECT quantity FROM user_inventory WHERE user_id = 'usr-f6-1' AND item_id = 'consumable_hint_scroll'" ) assert cur.fetchone()[0] == 2 def test_f6_2_consuming_item_decrements_quantity(self, db_conn): credit_sqlite_gold(db_conn, "usr-f6-2", 300) execute_sqlite_purchase(db_conn, "usr-f6-2", "consumable_hint_scroll", 2) res = use_sqlite_item(db_conn, "usr-f6-2", "consumable_hint_scroll") assert res.remaining_quantity == 1 def test_f6_3_consuming_last_item_removes_from_inventory(self, db_conn): credit_sqlite_gold(db_conn, "usr-f6-3", 100) execute_sqlite_purchase(db_conn, "usr-f6-3", "consumable_hint_scroll", 1) res = use_sqlite_item(db_conn, "usr-f6-3", "consumable_hint_scroll") assert res.remaining_quantity == 0 cur = db_conn.cursor() cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = 'usr-f6-3'") assert cur.fetchone()[0] == 0 def test_f6_4_inventory_item_default_equipped_is_false(self, db_conn): credit_sqlite_gold(db_conn, "usr-f6-4", 250) res = execute_sqlite_purchase(db_conn, "usr-f6-4", "cosmetic_theme_amber", 1) assert res.inventory_item.is_equipped is False def test_f6_5_inventory_retrieval_returns_owned_items(self, db_conn): credit_sqlite_gold(db_conn, "usr-f6-5", 500) execute_sqlite_purchase(db_conn, "usr-f6-5", "consumable_streak_freeze", 1) execute_sqlite_purchase(db_conn, "usr-f6-5", "gift_starflower_tea", 1) cur = db_conn.cursor() cur.execute("SELECT item_id, quantity FROM user_inventory WHERE user_id = 'usr-f6-5'") items = cur.fetchall() assert len(items) == 2 # --- F7: Desktop Window OS Integration --- def test_f7_1_store_window_id_validity(self): valid_windows = {"queue", "journey", "terminal", "computer", "store", "companion"} assert "store" in valid_windows def test_f7_2_store_window_dimensions_valid(self): width, height = 850, 600 assert width >= 800 assert height >= 500 def test_f7_3_store_icon_name(self): icon = "Store" assert icon in ["Store", "ShoppingBag", "Coins"] def test_f7_4_store_taskbar_label(self): title = "Store" assert "Emporium" in title or "Store" in title def test_f7_5_store_route_path(self): api_path = "/api/store/items" assert api_path.startswith("/api/store") # --- F8: Storefront Desktop Application UI Contract --- def test_f8_1_catalog_category_filtering(self): items = [i for i in BACKEND_STORE_CATALOG if i.category == "consumable"] assert all(i.category == "consumable" for i in items) def test_f8_2_affordance_predicate(self): def can_afford(bal: int, price: int) -> bool: return bal >= price assert can_afford(100, 150) is False assert can_afford(150, 150) is True def test_f8_3_lore_field_length(self): for item in BACKEND_STORE_CATALOG: assert len(item.lore) > 10 def test_f8_4_price_format_verification(self): price = 150 formatted = f"{price}g" assert formatted == "150g" def test_f8_5_category_tabs_list(self): tabs = ["all", "consumable", "cosmetic", "companion_gift"] assert len(tabs) == 4 # --- F9: Player Inventory Vault UI Contract --- def test_f9_1_inventory_action_type_routing(self): def action_for_category(cat: str) -> str: return {"consumable": "Consume", "cosmetic": "Equip", "companion_gift": "Gift"}[cat] assert action_for_category("consumable") == "Consume" assert action_for_category("cosmetic") == "Equip" assert action_for_category("companion_gift") == "Gift" def test_f9_2_stack_display_badge(self): def badge(q: int) -> str: return f"x{q}" if q > 1 else "" assert badge(1) == "" assert badge(3) == "x3" def test_f9_3_vault_enrichment_with_catalog(self, db_conn): credit_sqlite_gold(db_conn, "usr-f9-3", 150) execute_sqlite_purchase(db_conn, "usr-f9-3", "gift_silk_shawl", 1) cur = db_conn.cursor() cur.execute("SELECT item_id FROM user_inventory WHERE user_id = 'usr-f9-3'") item_id = cur.fetchone()[0] cat_match = next(c for c in BACKEND_STORE_CATALOG if c.id == item_id) assert cat_match.name == "Embroidered Silver Shawl" def test_f9_4_empty_vault_handling(self, db_conn): cur = db_conn.cursor() cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = 'usr-empty'") assert cur.fetchone()[0] == 0 def test_f9_5_vault_filter_by_category(self): test_inv = ["consumable_streak_freeze", "gift_starflower_tea"] cat_map = {i.id: i.category for i in BACKEND_STORE_CATALOG} consumables = [i for i in test_inv if cat_map[i] == "consumable"] assert consumables == ["consumable_streak_freeze"] # --- F10: Live Gold Counter Widget Contract --- def test_f10_1_gold_counter_format(self): assert f"{150}g" == "150g" def test_f10_2_gold_counter_non_negative(self): def sanitize(g: int) -> int: return max(0, g) assert sanitize(-20) == 0 assert sanitize(50) == 50 def test_f10_3_gold_counter_updates_after_purchase(self, db_conn): credit_sqlite_gold(db_conn, "usr-f10-3", 200) res = execute_sqlite_purchase(db_conn, "usr-f10-3", "consumable_streak_freeze", 1) assert res.new_balance == 50 def test_f10_4_gold_counter_zero_initial(self, db_conn): curr = get_sqlite_currency(db_conn, "usr-f10-4") assert curr.gold == 0 def test_f10_5_gold_tooltip_format(self): curr = PlayerCurrency(gold=100, lifetime_earned=250, updated_at="2026-10-16T12:00:00Z") tooltip = f"Gold: {curr.gold} (Lifetime: {curr.lifetime_earned})" assert tooltip == "Gold: 100 (Lifetime: 250)" # --- F11: Princess Aurelia Companion Gifting --- def test_f11_1_starflower_tea_awards_15_bond_points(self): tea = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_starflower_tea") assert tea.effect_payload["bond_points"] == 15 assert tea.effect_payload["emotion"] == "smiling_warmly" def test_f11_2_silk_shawl_awards_30_bond_points(self): shawl = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_silk_shawl") assert shawl.effect_payload["bond_points"] == 30 assert shawl.effect_payload["emotion"] == "smiling_warmly" def test_f11_3_music_box_awards_60_bond_points(self): box = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_music_box") assert box.effect_payload["bond_points"] == 60 assert box.effect_payload["emotion"] == "excited_expression" def test_f11_4_sanctuary_pendant_awards_100_bond_points(self): pendant = next(i for i in BACKEND_STORE_CATALOG if i.id == "gift_elixir_pendant") assert pendant.effect_payload["bond_points"] == 100 assert pendant.effect_payload["emotion"] == "excited_expression" def test_f11_5_gifting_consumes_inventory_unit(self, db_conn): credit_sqlite_gold(db_conn, "usr-f11-5", 100) execute_sqlite_purchase(db_conn, "usr-f11-5", "gift_starflower_tea", 1) res = use_sqlite_item(db_conn, "usr-f11-5", "gift_starflower_tea") assert res.remaining_quantity == 0 # --- F12: Desktop Cosmetics Activation --- def test_f12_1_crt_scanlines_payload(self): crt = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_crt_scanlines") assert crt.effect_payload["overlay_class"] == "crt-scanlines-active" def test_f12_2_amber_theme_payload(self): amber = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_theme_amber") assert amber.effect_payload["theme_id"] == "amber" def test_f12_3_cyber_theme_payload(self): cyber = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_theme_cyber") assert cyber.effect_payload["theme_id"] == "cyber" def test_f12_4_wallpaper_payload(self): wp = next(i for i in BACKEND_STORE_CATALOG if i.id == "cosmetic_wallpaper_sanctuary") assert wp.effect_payload["wallpaper_url"].endswith(".webp") def test_f12_5_equipping_cosmetic_updates_flag(self, db_conn): credit_sqlite_gold(db_conn, "usr-f12-5", 250) execute_sqlite_purchase(db_conn, "usr-f12-5", "cosmetic_theme_amber", 1) with db_conn: db_conn.execute("UPDATE user_inventory SET is_equipped = 1 WHERE user_id = 'usr-f12-5'") cur = db_conn.cursor() cur.execute("SELECT is_equipped FROM user_inventory WHERE user_id = 'usr-f12-5'") assert cur.fetchone()[0] == 1 # --- F13: Streak Freeze Consumable Effect --- def test_f13_1_streak_freeze_delta_2_protected(self): now = datetime.now(UTC).date() two_days_ago = (now - timedelta(days=2)).isoformat() streak_data = { "current_streak": 5, "longest_streak": 5, "last_active_date": two_days_ago, "streak_freeze_count": 1, } res = evaluate_srs_streak_freeze(streak_data, now) assert res["current_streak"] == 5 assert res["streak_freeze_count"] == 0 assert res["streak_freeze_consumed"] is True def test_f13_2_streak_freeze_delta_2_unprotected_resets(self): now = datetime.now(UTC).date() two_days_ago = (now - timedelta(days=2)).isoformat() streak_data = { "current_streak": 5, "longest_streak": 5, "last_active_date": two_days_ago, "streak_freeze_count": 0, } res = evaluate_srs_streak_freeze(streak_data, now) assert res["current_streak"] == 0 def test_f13_3_consecutive_day_keeps_freeze_untouched(self): now = datetime.now(UTC).date() yesterday = (now - timedelta(days=1)).isoformat() streak_data = { "current_streak": 5, "longest_streak": 5, "last_active_date": yesterday, "streak_freeze_count": 1, } res = evaluate_srs_streak_freeze(streak_data, now) assert res["current_streak"] == 5 assert res["streak_freeze_count"] == 1 def test_f13_4_multi_day_absence_resets_streak(self): now = datetime.now(UTC).date() three_days_ago = (now - timedelta(days=3)).isoformat() streak_data = { "current_streak": 5, "longest_streak": 5, "last_active_date": three_days_ago, "streak_freeze_count": 1, } res = evaluate_srs_streak_freeze(streak_data, now) assert res["current_streak"] == 0 def test_f13_5_consuming_streak_freeze_decrements_stack(self, db_conn): credit_sqlite_gold(db_conn, "usr-f13-5", 200) execute_sqlite_purchase(db_conn, "usr-f13-5", "consumable_streak_freeze", 1) res = use_sqlite_item(db_conn, "usr-f13-5", "consumable_streak_freeze") assert res.remaining_quantity == 0 # --- F14: Comprehensive Automated Testing & Verification --- def test_f14_1_deterministic_in_memory_isolation(self, db_conn): assert get_sqlite_currency(db_conn, "usr-iso").gold == 0 def test_f14_2_pydantic_schema_validation(self): curr = PlayerCurrency(gold=50, lifetime_earned=50, updated_at="2026-10-16T10:00:00Z") assert curr.gold == 50 def test_f14_3_pydantic_negative_gold_rejected(self): with pytest.raises(ValidationError): PlayerCurrency(gold=-1, lifetime_earned=0, updated_at="2026-10-16T10:00:00Z") def test_f14_4_catalog_pricing_immutability(self): for item in BACKEND_STORE_CATALOG: assert item.price > 0 def test_f14_5_transaction_schema_integrity(self): tx = StoreTransaction( id="tx-1", user_id="u1", item_id="i1", item_name="Item 1", price=50, quantity=1, total_price=50, balance_after=0, status="completed", timestamp="2026-10-16T10:00:00Z", ) assert tx.status == "completed" # ============================================================================ # TIER 2: BOUNDARY & CORNER CASES (>= 5 TEST CASES COVERING SYSTEM EDGES) # ============================================================================ class TestTier2BoundaryAndCornerCases: @pytest.fixture def db_conn(self): conn = sqlite3.connect(":memory:") create_sqlite_store_tables(conn) yield conn conn.close() def test_t2_1_exact_balance_boundary(self, db_conn): """User with exact funds (150g) purchases 150g item; balance becomes exactly 0g.""" credit_sqlite_gold(db_conn, "usr-t2-1", 150) res = execute_sqlite_purchase(db_conn, "usr-t2-1", "consumable_streak_freeze", 1) assert res.new_balance == 0 assert get_sqlite_currency(db_conn, "usr-t2-1").gold == 0 def test_t2_2_insufficient_balance_off_by_one(self, db_conn): """User with 149g attempts 150g item; rejected with 0 balance mutation.""" credit_sqlite_gold(db_conn, "usr-t2-2", 149) with pytest.raises(ValueError, match="Insufficient gold balance"): execute_sqlite_purchase(db_conn, "usr-t2-2", "consumable_streak_freeze", 1) assert get_sqlite_currency(db_conn, "usr-t2-2").gold == 149 def test_t2_3_zero_balance_purchase_rejected(self, db_conn): """User with 0g attempts purchase of cheapest item (50g); rejected.""" with pytest.raises(ValueError, match="Insufficient gold balance"): execute_sqlite_purchase(db_conn, "usr-t2-3", "consumable_campfire_stew", 1) def test_t2_4_negative_or_zero_purchase_quantity_rejected(self, db_conn): """Non-positive quantities are rejected.""" credit_sqlite_gold(db_conn, "usr-t2-4", 500) with pytest.raises(ValueError, match="quantity must be positive"): execute_sqlite_purchase(db_conn, "usr-t2-4", "consumable_hint_scroll", 0) with pytest.raises(ValueError, match="quantity must be positive"): execute_sqlite_purchase(db_conn, "usr-t2-4", "consumable_hint_scroll", -1) def test_t2_5_extreme_balance_values(self, db_conn): """Large balances handle purchases cleanly without integer overflow.""" credit_sqlite_gold(db_conn, "usr-t2-5", 10_000_000) res = execute_sqlite_purchase(db_conn, "usr-t2-5", "consumable_hint_scroll", 10) assert res.new_balance == 10_000_000 - 750 assert res.inventory_item.quantity == 10 def test_t2_6_streak_freeze_delta_boundaries(self): """Comprehensive edge testing of streak freeze delta values.""" now = datetime.now(UTC).date() # Delta 0 (same day) res0 = evaluate_srs_streak_freeze( {"current_streak": 3, "last_active_date": now.isoformat(), "streak_freeze_count": 1}, now, ) assert res0["current_streak"] == 3 assert res0["streak_freeze_count"] == 1 # Delta 1 (consecutive) yest = (now - timedelta(days=1)).isoformat() res1 = evaluate_srs_streak_freeze( {"current_streak": 3, "last_active_date": yest, "streak_freeze_count": 1}, now, ) assert res1["current_streak"] == 3 assert res1["streak_freeze_count"] == 1 # Delta 2 (missed 1 day with freeze) two_ago = (now - timedelta(days=2)).isoformat() res2 = evaluate_srs_streak_freeze( {"current_streak": 3, "last_active_date": two_ago, "streak_freeze_count": 1}, now, ) assert res2["current_streak"] == 3 assert res2["streak_freeze_count"] == 0 assert res2["streak_freeze_consumed"] is True # Delta 3 (missed 2 days even with freeze) three_ago = (now - timedelta(days=3)).isoformat() res3 = evaluate_srs_streak_freeze( {"current_streak": 3, "last_active_date": three_ago, "streak_freeze_count": 1}, now, ) assert res3["current_streak"] == 0 def test_t2_7_consuming_unowned_item_rejected(self, db_conn): with pytest.raises(ValueError, match="not available in inventory"): use_sqlite_item(db_conn, "usr-t2-7", "consumable_streak_freeze") def test_t2_8_purchasing_unknown_catalog_id_rejected(self, db_conn): credit_sqlite_gold(db_conn, "usr-t2-8", 500) with pytest.raises(KeyError, match="not found in catalog"): execute_sqlite_purchase(db_conn, "usr-t2-8", "unknown_item_999", 1) def test_t2_9_two_successive_purchases_leaving_exact_zero(self, db_conn): credit_sqlite_gold(db_conn, "usr-t2-9", 125) # 75g + 50g execute_sqlite_purchase(db_conn, "usr-t2-9", "consumable_hint_scroll", 1) execute_sqlite_purchase(db_conn, "usr-t2-9", "consumable_campfire_stew", 1) assert get_sqlite_currency(db_conn, "usr-t2-9").gold == 0 def test_t2_10_concurrent_insufficient_purchase_fails_gracefully(self, db_conn): credit_sqlite_gold(db_conn, "usr-t2-10", 150) execute_sqlite_purchase(db_conn, "usr-t2-10", "consumable_streak_freeze", 1) # Attempt second purchase with depleted funds with pytest.raises(ValueError, match="Insufficient gold balance"): execute_sqlite_purchase(db_conn, "usr-t2-10", "consumable_streak_freeze", 1) # ============================================================================ # TIER 3: CROSS-FEATURE COMBINATIONS (PAIRWISE INTERACTIONS) # ============================================================================ class TestTier3CrossFeatureCombinations: @pytest.fixture def db_conn(self): conn = sqlite3.connect(":memory:") create_sqlite_store_tables(conn) yield conn conn.close() def test_t3_1_earn_buy_equip_verify_effect(self, db_conn): """Earn gold from reviews and challenge -> Buy CRT shader -> Equip -> Verify state.""" user = "usr-t3-1" # 1. Earn gold: 4 Good reviews (100g) + 1 Challenge (100g) = 200g credit_sqlite_gold(db_conn, user, 100) credit_sqlite_gold(db_conn, user, 100) assert get_sqlite_currency(db_conn, user).gold == 200 # 2. Buy CRT scanlines cosmetic (200g) res = execute_sqlite_purchase(db_conn, user, "cosmetic_crt_scanlines", 1) assert res.new_balance == 0 # 3. Equip CRT scanlines in database with db_conn: db_conn.execute( "UPDATE user_inventory SET is_equipped = 1 WHERE user_id = ? AND item_id = 'cosmetic_crt_scanlines'", (user,), ) cur = db_conn.cursor() cur.execute( "SELECT is_equipped FROM user_inventory WHERE user_id = ? AND item_id = 'cosmetic_crt_scanlines'", (user,), ) assert cur.fetchone()[0] == 1 def test_t3_2_earn_buy_gift_verify_aurelia_bond(self, db_conn): """Earn gold from challenge -> Buy Starflower Tea -> Consume/gift -> Verify bond progression.""" user = "usr-t3-2" # 1. Earn 100g credit_sqlite_gold(db_conn, user, 100) # 2. Buy Starflower Tea (80g) res = execute_sqlite_purchase(db_conn, user, "gift_starflower_tea", 1) assert res.new_balance == 20 # 3. Present gift to Aurelia (consume unit) use_res = use_sqlite_item(db_conn, user, "gift_starflower_tea") assert use_res.effect_applied == "aurelia_gift" assert use_res.details["bond_points"] == 15 assert use_res.details["emotion"] == "smiling_warmly" assert use_res.remaining_quantity == 0 def test_t3_3_earn_buy_streak_freeze_miss_day_verify_shield(self, db_conn): """Earn 150g -> Buy Elixir of Frozen Time -> Miss day -> Shield protects streak.""" user = "usr-t3-3" credit_sqlite_gold(db_conn, user, 150) execute_sqlite_purchase(db_conn, user, "consumable_streak_freeze", 1) # Consume item to arm freeze use_sqlite_item(db_conn, user, "consumable_streak_freeze") # Simulate missed day (delta == 2) now = datetime.now(UTC).date() two_days_ago = (now - timedelta(days=2)).isoformat() streak = { "current_streak": 10, "longest_streak": 10, "last_active_date": two_days_ago, "streak_freeze_count": 1, } protected = evaluate_srs_streak_freeze(streak, now) assert protected["current_streak"] == 10 assert protected["streak_freeze_count"] == 0 assert protected["streak_freeze_consumed"] is True def test_t3_4_multi_category_purchases(self, db_conn): """Purchase items across all three categories in sequence.""" user = "usr-t3-4" credit_sqlite_gold(db_conn, user, 500) # Consumable (75g Hint Scroll) execute_sqlite_purchase(db_conn, user, "consumable_hint_scroll", 1) # Cosmetic (200g CRT Shader) execute_sqlite_purchase(db_conn, user, "cosmetic_crt_scanlines", 1) # Companion Gift (80g Starflower Tea) execute_sqlite_purchase(db_conn, user, "gift_starflower_tea", 1) # Remaining: 500 - 355 = 145g assert get_sqlite_currency(db_conn, user).gold == 145 cur = db_conn.cursor() cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = ?", (user,)) assert cur.fetchone()[0] == 3 def test_t3_5_cross_user_dual_mode_isolation(self, db_conn): """Ensure guest mode and authenticated mode user data do not collide.""" guest_id = "sandbox-user-id" auth_id = "firebase-jwt-uid-99" credit_sqlite_gold(db_conn, guest_id, 100) credit_sqlite_gold(db_conn, auth_id, 800) execute_sqlite_purchase(db_conn, guest_id, "consumable_hint_scroll", 1) execute_sqlite_purchase(db_conn, auth_id, "gift_elixir_pendant", 1) assert get_sqlite_currency(db_conn, guest_id).gold == 25 assert get_sqlite_currency(db_conn, auth_id).gold == 300 # ============================================================================ # TIER 4: REAL-WORLD SCENARIOS (LEARNER JOURNEYS) # ============================================================================ class TestTier4RealWorldScenarios: @pytest.fixture def db_conn(self): conn = sqlite3.connect(":memory:") create_sqlite_store_tables(conn) yield conn conn.close() def test_t4_1_scenario_1_the_novice_wayfarer(self, db_conn): """Scenario 1: Start 0g -> Solve reviews -> Unaffordable rejection -> Buy affordable.""" user = "novice-learner" # 1. Start with 0g assert get_sqlite_currency(db_conn, user).gold == 0 # 2. Complete 1 Easy (+35g), 1 Good (+25g), 1 Hard (+15g) = 75g credit_sqlite_gold(db_conn, user, 35) credit_sqlite_gold(db_conn, user, 25) credit_sqlite_gold(db_conn, user, 15) assert get_sqlite_currency(db_conn, user).gold == 75 # 3. Attempt to buy Elixir of Frozen Time (150g) -> Rejected with pytest.raises(ValueError, match="Insufficient gold balance"): execute_sqlite_purchase(db_conn, user, "consumable_streak_freeze", 1) assert get_sqlite_currency(db_conn, user).gold == 75 # 4. Buy Archivist's Hint Scroll (75g) -> Succeeded res = execute_sqlite_purchase(db_conn, user, "consumable_hint_scroll", 1) assert res.new_balance == 0 assert res.inventory_item.item_id == "consumable_hint_scroll" def test_t4_2_scenario_2_the_guardians_devotion(self, db_conn): """Scenario 2: Complete challenge + reviews -> Buy Shawl -> Gift to Aurelia.""" user = "guardian-user" # 1. Earn 100g (challenge) + 3 Good reviews (75g) = 175g credit_sqlite_gold(db_conn, user, 100) for _ in range(3): credit_sqlite_gold(db_conn, user, 25) assert get_sqlite_currency(db_conn, user).gold == 175 # 2. Buy Embroidered Silver Shawl (150g) -> Balance 25g res = execute_sqlite_purchase(db_conn, user, "gift_silk_shawl", 1) assert res.new_balance == 25 # 3. Present gift to Princess Aurelia use_res = use_sqlite_item(db_conn, user, "gift_silk_shawl") assert use_res.effect_applied == "aurelia_gift" assert use_res.details["bond_points"] == 30 assert use_res.details["emotion"] == "smiling_warmly" # Inventory depleted cur = db_conn.cursor() cur.execute("SELECT COUNT(*) FROM user_inventory WHERE user_id = ?", (user,)) assert cur.fetchone()[0] == 0 def test_t4_3_scenario_3_the_spire_architect(self, db_conn): """Scenario 3: Intensive study -> Streak freeze -> Unaffordable theme -> Earn -> Buy theme.""" user = "spire-architect" # 1. Study: 5 Good reviews (125g) + Challenge (100g) = 225g for _ in range(5): credit_sqlite_gold(db_conn, user, 25) credit_sqlite_gold(db_conn, user, 100) assert get_sqlite_currency(db_conn, user).gold == 225 # 2. Buy Streak Freeze (150g) -> Balance 75g res1 = execute_sqlite_purchase(db_conn, user, "consumable_streak_freeze", 1) assert res1.new_balance == 75 # 3. Consume freeze use_sqlite_item(db_conn, user, "consumable_streak_freeze") # 4. Attempt to buy Amber Theme (250g) with 75g -> Rejected with pytest.raises(ValueError, match="Insufficient gold balance"): execute_sqlite_purchase(db_conn, user, "cosmetic_theme_amber", 1) assert get_sqlite_currency(db_conn, user).gold == 75 # 5. Earn 175g (5 Easy reviews x 35g) -> 75 + 175 = 250g for _ in range(5): credit_sqlite_gold(db_conn, user, 35) assert get_sqlite_currency(db_conn, user).gold == 250 # 6. Buy Amber Theme (250g) -> Success! res2 = execute_sqlite_purchase(db_conn, user, "cosmetic_theme_amber", 1) assert res2.new_balance == 0 assert res2.inventory_item.item_id == "cosmetic_theme_amber"
"""End-to-End opaque-box test suite for store and Inventory System.
Derived strictly from ORIGINAL_REQUEST.md and PROJECT.md specifications.
Covers 4-Tier methodology:
- Tier 1: Feature Coverage (F1 to F14 in isolation, >=5 tests each)
- Tier 2: Boundary & Corner Cases (>=5 tests covering 0 balance, negative inputs, max bounds, delta edges)
- Tier 3: Cross-Feature Combinations (pairwise interactions)
- Tier 4: Real-World Scenarios (learner journeys)
"""
import sqlite3
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
import pytest
from pydantic import BaseModel, Field, ValidationError
from srs_logic import _parse_streak_date
# ============================================================================
# Pydantic Interface Contracts (matching PROJECT.md § Interface Contracts)
# ============================================================================
StoreItemCategory = Literal["consumable", "cosmetic", "companion_gift"]
EffectType = Literal[
"streak_freeze",
"hint_scroll",
"focus_boost",
"wallpaper",
"crt_theme",
"palette_theme",
"aurelia_gift",
]
class PlayerCurrency(BaseModel):
gold: int = Field(ge=0, description="Current usable gold balance")
lifetime_earned: int = Field(ge=0, description="Total lifetime gold accumulated")
updated_at: str = Field(description="ISO 8601 timestamp of last update")
class StoreItem(BaseModel):
id: str
name: str
category: StoreItemCategory
price: int = Field(gt=0, description="Cost in gold; must be strictly positive")
lore: str
icon: str
effect_type: EffectType
effect_payload: dict[str, Any] = Field(default_factory=dict)
class InventoryItem(BaseModel):
item_id: str
quantity: int = Field(ge=1, description="Owned stack count; >= 1")
is_equipped: bool = False
acquired_at: str
updated_at: str
class StoreTransaction(BaseModel):
id: str
user_id: str
item_id: str
item_name: str
price: int = Field(gt=0)
quantity: int = Field(gt=0)
total_price: int = Field(gt=0)
balance_after: int = Field(ge=0)
status: Literal["completed", "failed"]
timestamp: str
class PurchaseItemRequest(BaseModel):
item_id: str
quantity: int = Field(default=1, gt=0)
class PurchaseItemResponse(BaseModel):
success: bool
item: StoreItem
new_balance: int = Field(ge=0)
inventory_item: InventoryItem
class UseItemRequest(BaseModel):
item_id: str
class UseItemResponse(BaseModel):
success: bool
effect_applied: str
remaining_quantity: int = Field(ge=0)
details: dict[str, Any] = Field(default_factory=dict)
class EquipItemRequest(BaseModel):
item_id: str
is_equipped: bool = True