File size: 7,704 Bytes
aa1fcca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""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