"""Unit tests for store REST endpoints and earning hooks. Tests FastAPI endpoints in routers/store.py, reviews.py, and challenges.py using TestClient. """ import pytest from fastapi.testclient import TestClient import db from main import app AUTH_HEADERS = {"Authorization": "Bearer sandbox"} @pytest.fixture def client(): return TestClient(app) @pytest.fixture(autouse=True) def setup_user_state(): """Ensure clean initial user currency and streak for deterministic tests.""" db.increment_user_gold(0, "sandbox-user-id") yield class TestStoreEndpoints: def test_get_currency_initial(self, client): res = client.get("/api/currency", headers=AUTH_HEADERS) assert res.status_code == 200 data = res.json() assert "gold" in data assert "lifetime_earned" in data assert "updated_at" in data assert data["gold"] >= 0 def test_get_store_items_catalog(self, client): res = client.get("/api/store/items", headers=AUTH_HEADERS) assert res.status_code == 200 items = res.json() assert len(items) == 12 categories = {i["category"] for i in items} assert categories == {"consumable", "cosmetic", "companion_gift"} def test_get_inventory(self, client): res = client.get("/api/inventory", headers=AUTH_HEADERS) assert res.status_code == 200 assert isinstance(res.json(), list) def test_purchase_item_insufficient_funds_rejected(self, client): # Reset gold to low value by spending or testing against expensive item res = client.post( "/api/store/purchase", headers=AUTH_HEADERS, json={"item_id": "gift_elixir_pendant", "quantity": 999}, ) assert res.status_code == 400 assert "Insufficient gold balance to purchase item." in res.json()["detail"] def test_purchase_item_unknown_item_not_found(self, client): res = client.post( "/api/store/purchase", headers=AUTH_HEADERS, json={"item_id": "nonexistent_ancient_relic", "quantity": 1}, ) assert res.status_code == 404 assert "not found" in res.json()["detail"] def test_purchase_item_invalid_quantity_rejected(self, client): res = client.post( "/api/store/purchase", headers=AUTH_HEADERS, json={"item_id": "consumable_streak_freeze", "quantity": 0}, ) assert res.status_code in (400, 422) def test_successful_purchase_and_inventory_vault(self, client): # Credit sufficient gold db.increment_user_gold(1000, "sandbox-user-id") bal_before = db.get_user_currency("sandbox-user-id")["gold"] res = client.post( "/api/store/purchase", headers=AUTH_HEADERS, json={"item_id": "consumable_hint_scroll", "quantity": 1}, ) assert res.status_code == 200 data = res.json() assert data["success"] is True assert data["new_balance"] == bal_before - 75 assert data["inventory_item"]["item_id"] == "consumable_hint_scroll" assert data["inventory_item"]["quantity"] >= 1 # Check inventory endpoint reflects it inv_res = client.get("/api/inventory", headers=AUTH_HEADERS) assert inv_res.status_code == 200 inv_items = inv_res.json() assert any(i["item_id"] == "consumable_hint_scroll" for i in inv_items) def test_use_item_consumable_success(self, client): db.increment_user_gold(500, "sandbox-user-id") client.post( "/api/store/purchase", headers=AUTH_HEADERS, json={"item_id": "consumable_streak_freeze", "quantity": 1}, ) res = client.post( "/api/inventory/use", headers=AUTH_HEADERS, json={"item_id": "consumable_streak_freeze"}, ) assert res.status_code == 200 data = res.json() assert data["success"] is True assert data["effect_applied"] == "streak_freeze" def test_use_cosmetic_item_rejected(self, client): res = client.post( "/api/inventory/use", headers=AUTH_HEADERS, json={"item_id": "cosmetic_theme_amber"}, ) assert res.status_code == 400 assert "cosmetic and cannot be consumed" in res.json()["detail"] def test_equip_cosmetic_success(self, client): db.increment_user_gold(500, "sandbox-user-id") client.post( "/api/store/purchase", headers=AUTH_HEADERS, json={"item_id": "cosmetic_theme_amber", "quantity": 1}, ) res = client.post( "/api/inventory/equip", headers=AUTH_HEADERS, json={"item_id": "cosmetic_theme_amber", "is_equipped": True}, ) assert res.status_code == 200 data = res.json() assert data["success"] is True assert data["item_id"] == "cosmetic_theme_amber" assert data["is_equipped"] is True def test_equip_consumable_rejected(self, client): res = client.post( "/api/inventory/equip", headers=AUTH_HEADERS, json={"item_id": "consumable_streak_freeze", "is_equipped": True}, ) assert res.status_code == 400 assert "not a cosmetic item" in res.json()["detail"] def test_get_store_transactions(self, client): res = client.get("/api/store/transactions", headers=AUTH_HEADERS) assert res.status_code == 200 assert isinstance(res.json(), list) class TestEarningHooks: @pytest.mark.parametrize( "rating,expected_gold", [(1, 5), (2, 15), (3, 25), (4, 35)], ) def test_review_complete_awards_rating_scaled_gold(self, client, rating, expected_gold): bal_before = db.get_user_currency("sandbox-user-id")["gold"] req_body = { "review_id": "prob-contains-duplicate", "rating": rating, "fsrs_state": 0, "fsrs_step": 0, "fsrs_stability": 0.0, "fsrs_difficulty": 0.0, "fsrs_elapsed_days": 0, "fsrs_scheduled_days": 0, "fsrs_reps": 0, "fsrs_lapses": 0, "last_reviewed": None, } res = client.post("/api/reviews/complete", headers=AUTH_HEADERS, json=req_body) assert res.status_code == 200 data = res.json() assert data["success"] is True assert data["gold_awarded"] == expected_gold assert data["new_balance"] == bal_before + expected_gold from unittest.mock import patch @patch("sandbox.run_python_sandbox_async") @patch("llm_reviewer.generate_daily_python_challenge_async") def test_challenge_python_submit_awards_100_gold(self, mock_gen, mock_sandbox, client): mock_gen.return_value = { "title": "Mock Daily Python Challenge", "points": 100, "test_cases": [{"input": [], "expected": 42}], } mock_sandbox.return_value = { "success": True, "results": [{"status": "passed"}], "sandbox_type": "local", } bal_before = db.get_user_currency("sandbox-user-id")["gold"] req_body = { "code": "def solve(): return 42", "challenge_index": 0, } res = client.post("/api/challenges/python/submit", headers=AUTH_HEADERS, json=req_body) assert res.status_code == 200 data = res.json() assert data["all_passed"] is True assert data["gold_awarded"] == 100 assert data["new_balance"] == bal_before + 100