Spaces:
Sleeping
Sleeping
Download tests/test_gamification.py from baljot07/studiq-backend: direct link, hf CLI and curl.
- Browser
- Download file 7.82 kB
-
https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/tests/test_gamification.py
- Command line
-
hf download hf://spaces/baljot07/studiq-backend/tests/test_gamification.py
-
curl -L -o test_gamification.py https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/tests/test_gamification.py
7.82 kB
| import pytest | |
| import uuid | |
| from unittest.mock import patch, MagicMock | |
| from datetime import datetime | |
| import pytz | |
| from httpx import AsyncClient | |
| from sqlalchemy import select | |
| from app.models.user import User | |
| from app.services.xp_service import award_xp | |
| from app.services.achievement_service import check_achievements, get_all_badges | |
| from tests.conftest import create_authenticated_user, TestSessionLocal | |
| pytestmark = pytest.mark.asyncio | |
| async def test_award_xp_and_coins(client: AsyncClient): | |
| """Test that award_xp correctly increases XP, weekly_xp, and coins.""" | |
| user_id, token = await create_authenticated_user(client) | |
| async with TestSessionLocal() as db_session: | |
| # Retrieve user from DB | |
| result = await db_session.execute(select(User).where(User.id == uuid.UUID(user_id))) | |
| user = result.scalar_one() | |
| # Initial assertions | |
| assert user.xp_total == 0 | |
| assert user.weekly_xp == 0 | |
| assert user.coins == 0 | |
| # Award chat_message | |
| res = await award_xp(user, "chat_message") | |
| await db_session.commit() | |
| assert res["xp_gained"] == 5 | |
| assert res["coins_gained"] == 1 | |
| assert user.xp_total == 5 | |
| assert user.weekly_xp == 5 | |
| assert user.coins == 1 | |
| async def test_streak_milestone_bonus(): | |
| """Test 7-day streak milestone coin bonus (+50 coins).""" | |
| async with TestSessionLocal() as db_session: | |
| user = User( | |
| name="Test Student", | |
| email="test_milestone@example.com", | |
| streak_days=7, | |
| xp_total=0, | |
| weekly_xp=0, | |
| coins=0 | |
| ) | |
| db_session.add(user) | |
| await db_session.commit() | |
| # Award streak_day | |
| res = await award_xp(user, "streak_day") | |
| assert res["coins_gained"] == 55 # 5 standard + 50 bonus | |
| assert user.coins == 55 | |
| async def test_achievement_late_night_scholar(): | |
| """Test unlocking Late Night Scholar badge when time is between 12 AM and 4 AM IST.""" | |
| async with TestSessionLocal() as db_session: | |
| user = User(name="Night Owl", email="owl@example.com", streak_days=0, xp_total=0, weekly_xp=0, coins=0, achievements={}) | |
| db_session.add(user) | |
| await db_session.commit() | |
| # Mock time to 2:00 AM IST | |
| ist = pytz.timezone("Asia/Kolkata") | |
| mock_now = datetime(2026, 6, 3, 2, 0, 0, tzinfo=ist) | |
| with patch("app.services.achievement_service.datetime") as mock_datetime: | |
| mock_datetime.now.return_value = mock_now | |
| unlocked = await check_achievements(user, "chat_message") | |
| assert "late_night_scholar" in unlocked | |
| assert user.achievements["late_night_scholar"]["unlocked"] is True | |
| async def test_achievement_code_master(): | |
| """Test unlocking Code Master after 10 coding exercises.""" | |
| async with TestSessionLocal() as db_session: | |
| user = User(name="Coder", email="coder@example.com", streak_days=0, xp_total=0, weekly_xp=0, coins=0, achievements={}) | |
| db_session.add(user) | |
| await db_session.commit() | |
| for i in range(9): | |
| unlocked = await check_achievements(user, "coding_exercise_completed") | |
| assert not unlocked | |
| assert user.achievements["code_master"]["progress"] == i + 1 | |
| unlocked = await check_achievements(user, "coding_exercise_completed") | |
| assert "code_master" in unlocked | |
| assert user.achievements["code_master"]["unlocked"] is True | |
| assert user.achievements["code_master"]["progress"] == 10 | |
| async def test_leaderboard_endpoints(client: AsyncClient): | |
| """Test weekly and global leaderboard GET requests.""" | |
| # Create test users | |
| u1_id, t1 = await create_authenticated_user(client) | |
| u2_id, t2 = await create_authenticated_user(client) | |
| async with TestSessionLocal() as db_session: | |
| # Update u1 to have high XP/weekly_xp and university | |
| r1 = await db_session.execute(select(User).where(User.id == uuid.UUID(u1_id))) | |
| user1 = r1.scalar_one() | |
| user1.xp_total = 500 | |
| user1.weekly_xp = 300 | |
| user1.university_name = "Delhi University" | |
| # Update u2 to have lower XP and same university | |
| r2 = await db_session.execute(select(User).where(User.id == uuid.UUID(u2_id))) | |
| user2 = r2.scalar_one() | |
| user2.xp_total = 100 | |
| user2.weekly_xp = 50 | |
| user2.university_name = "Delhi University" | |
| await db_session.commit() | |
| # Test Weekly Leaderboard (with DU headers) | |
| headers1 = {"Authorization": f"Bearer {t1}"} | |
| response = await client.get("/api/v1/leaderboard/weekly", headers=headers1) | |
| assert response.status_code == 200 | |
| data = response.json() | |
| assert data["scope"] == "university" | |
| assert data["university"] == "Delhi University" | |
| assert len(data["leaderboard"]) >= 2 | |
| assert data["leaderboard"][0]["user_id"] == str(u1_id) | |
| assert data["leaderboard"][0]["weekly_xp"] == 300 | |
| # Test Global Leaderboard | |
| response_global = await client.get("/api/v1/leaderboard/global", headers=headers1) | |
| assert response_global.status_code == 200 | |
| data_global = response_global.json() | |
| assert len(data_global["leaderboard"]) >= 2 | |
| assert data_global["leaderboard"][0]["user_id"] == str(u1_id) | |
| assert data_global["leaderboard"][0]["xp_total"] == 500 | |
| async def test_achievements_api_endpoint(client: AsyncClient): | |
| """Test fetching all badges and checking unlock status via GET /achievements.""" | |
| user_id, token = await create_authenticated_user(client) | |
| headers = {"Authorization": f"Bearer {token}"} | |
| response = await client.get("/api/v1/achievements", headers=headers) | |
| assert response.status_code == 200 | |
| data = response.json() | |
| assert "achievements" in data | |
| assert len(data["achievements"]) == len(get_all_badges()) | |
| # All achievements should be locked initially | |
| for badge in data["achievements"]: | |
| assert badge["unlocked"] is False | |
| assert badge["progress"] == 0 | |
| async def test_store_purchase_endpoints(client: AsyncClient): | |
| """Test buying streak freezes and premium UI themes.""" | |
| user_id, token = await create_authenticated_user(client) | |
| headers = {"Authorization": f"Bearer {token}"} | |
| # Try buying streak freeze with 0 coins -> should fail 400 | |
| res_fail = await client.post("/api/v1/store/buy/streak-freeze", headers=headers) | |
| assert res_fail.status_code == 400 | |
| assert "Insufficient coins" in res_fail.json()["detail"] | |
| async with TestSessionLocal() as db_session: | |
| # Give user 300 coins | |
| result = await db_session.execute(select(User).where(User.id == uuid.UUID(user_id))) | |
| user = result.scalar_one() | |
| user.coins = 300 | |
| user.streak_freeze_available = 0 | |
| await db_session.commit() | |
| # Buy Streak Freeze successfully | |
| res_ok = await client.post("/api/v1/store/buy/streak-freeze", headers=headers) | |
| assert res_ok.status_code == 200 | |
| assert res_ok.json()["coins_remaining"] == 200 | |
| assert res_ok.json()["streak_freezes_owned"] == 1 | |
| # Buy Theme successfully (costs 200) | |
| res_theme = await client.post( | |
| "/api/v1/store/buy/theme", | |
| headers=headers, | |
| json={"theme_id": "cyberpunk"} | |
| ) | |
| assert res_theme.status_code == 200 | |
| assert res_theme.json()["coins_remaining"] == 0 | |
| assert "cyberpunk" in res_theme.json()["purchased_themes"] | |
| # Try buying the same theme again -> should fail 400 | |
| res_theme_fail = await client.post( | |
| "/api/v1/store/buy/theme", | |
| headers=headers, | |
| json={"theme_id": "cyberpunk"} | |
| ) | |
| assert res_theme_fail.status_code == 400 | |
| assert "already own" in res_theme_fail.json()["detail"] | |