Spaces:
Running on T4
Running on T4
File size: 10,077 Bytes
2756f0f 6437539 2756f0f 6437539 2756f0f | 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 215 216 217 218 219 220 221 222 223 224 225 226 | """B1 GET /me, B2 PATCH /me, B5 DELETE /me."""
import os
import uuid
import boto3
import pytest
from botocore.exceptions import ClientError
from sqlalchemy import text
from app.core.database import get_engine
from tests.helpers import bearer, register
async def _sql(statement: str, **params):
async with get_engine().begin() as conn:
return (await conn.execute(text(statement), params))
async def _make_team(coach_id: str, code: str = "KDA-4821") -> str:
team_id = str(uuid.uuid4())
await _sql("INSERT INTO teams (id, code, name, coach_id, coaching) VALUES (:id, :code, :name, :coach, 'both')",
id=team_id, code=code, name="Karachi Diamond Academy", coach=coach_id)
return team_id
async def _make_upload(owner_id: str, key: str) -> str:
upload_id = str(uuid.uuid4())
await _sql("INSERT INTO uploads (id, owner_id, kind, object_key, content_type, size_bytes, attached_at) "
"VALUES (:id, :owner, 'video', :key, 'video/mp4', 10, now())", id=upload_id, owner=owner_id, key=key)
return upload_id
async def _make_session(owner_id: str) -> None:
upload_id = await _make_upload(owner_id, f"videos/{owner_id}/{uuid.uuid4()}.mp4")
await _sql("INSERT INTO sessions (owner_id, is_self, athlete, mode, video_upload_id, duration_sec, fps, marks, "
"analyzed_at) VALUES (:owner, true, '{}', 'h', :upload, 3.5, 30, '{}', now())",
owner=owner_id, upload=upload_id)
def _s3():
return boto3.client("s3", endpoint_url=os.environ["STORAGE_ENDPOINT"], region_name="us-east-1",
aws_access_key_id="test", aws_secret_access_key="test")
# B1 GET /me
async def test_me_without_team(client):
account = await register(client)
response = await client.get("/v1/me", headers=account["headers"])
assert response.status_code == 200
body = response.json()
assert body["user"] == account["user"]
assert body["team"] is None
assert body["entitlement"] == {"plan": "free", "weekly_limit": 20, "used_this_week": 0, "left": 20,
"window_days": 7}
async def test_me_player_and_coach_see_team(client):
coach = await register(client, role="coach")
await client.patch("/v1/me", headers=coach["headers"], json={"profile": {"name": "Imran Baig"}})
team_id = await _make_team(coach["user"]["id"])
player = await register(client)
await _sql("UPDATE accounts SET team_id = :team WHERE id = :id", team=team_id, id=player["user"]["id"])
player_me = (await client.get("/v1/me", headers=player["headers"])).json()
assert player_me["user"]["team_code"] == "KDA-4821"
assert player_me["team"]["code"] == "KDA-4821"
assert player_me["team"]["coach_name"] == "Imran Baig"
assert player_me["team"]["coach_id"] == coach["user"]["id"]
assert set(player_me["team"]) == {"id", "code", "name", "coach_id", "coach_name", "coaching", "created_at"}
coach_me = (await client.get("/v1/me", headers=coach["headers"])).json()
assert coach_me["team"]["id"] == team_id
assert coach_me["user"]["team_code"] is None
async def test_me_counts_usage(client):
account = await register(client)
await _make_session(account["user"]["id"])
entitlement = (await client.get("/v1/me", headers=account["headers"])).json()["entitlement"]
assert entitlement["used_this_week"] == 1 and entitlement["left"] == 19
@pytest.mark.parametrize("headers", [{}, bearer("not-a-jwt")])
async def test_me_requires_token(client, headers):
response = await client.get("/v1/me", headers=headers)
assert response.status_code == 401
assert response.json()["error"]["code"] == "UNAUTHENTICATED"
# B2 PATCH /me
async def test_update_me(client):
account = await register(client)
patch = {"role": "coach", "focus": "h", "unit": "metric", "private_videos": False,
"profile": {"name": " Ahmed Rehman ", "age": 15, "height_cm": 168.25, "weight_kg": 60,
"bats": "R", "throws": "L", "level": "high_school"}}
response = await client.patch("/v1/me", headers=account["headers"], json=patch)
assert response.status_code == 200
user = response.json()["user"]
assert set(response.json()) == {"user"}
assert user["role"] == "coach" and user["focus"] == "h" and user["unit"] == "metric"
assert user["private_videos"] is False
assert user["profile"] == {"name": "Ahmed Rehman", "age": 15, "height_cm": 168.2, "weight_kg": 60.0,
"bats": "R", "throws": "L", "level": "high_school"}
assert (await client.get("/v1/me", headers=account["headers"])).json()["user"] == user
async def test_update_me_is_partial_and_nulls_clear_profile_fields(client):
account = await register(client)
await client.patch("/v1/me", headers=account["headers"],
json={"focus": "p", "profile": {"name": "Ali Khan", "age": 20, "height_cm": 180}})
response = await client.patch("/v1/me", headers=account["headers"], json={"profile": {"age": None}})
user = response.json()["user"]
assert user["focus"] == "p"
assert user["profile"]["name"] == "Ali Khan" and user["profile"]["age"] is None
assert user["profile"]["height_cm"] == 180.0
cleared = await client.patch("/v1/me", headers=account["headers"], json={"profile": {"name": ""}})
assert cleared.json()["user"]["profile"]["name"] == ""
async def test_update_me_same_role_is_allowed_when_locked(client):
account = await register(client)
await _make_session(account["user"]["id"])
response = await client.patch("/v1/me", headers=account["headers"], json={"role": "player"})
assert response.status_code == 200
@pytest.mark.parametrize("patch, field", [
({"profile": {"age": 4}}, "profile.age"),
({"profile": {"age": 71}}, "profile.age"),
({"profile": {"age": 15.5}}, "profile.age"),
({"profile": {"height_cm": 89}}, "profile.height_cm"),
({"profile": {"height_cm": 231}}, "profile.height_cm"),
({"profile": {"weight_kg": 19}}, "profile.weight_kg"),
({"profile": {"weight_kg": 201}}, "profile.weight_kg"),
({"profile": {"bats": "X"}}, "profile.bats"),
({"profile": {"throws": "S"}}, "profile.throws"),
({"profile": {"level": "High school"}}, "profile.level"),
({"profile": {"name": "A"}}, "profile.name"),
({"profile": {"name": "x" * 81}}, "profile.name"),
({"profile": {"name": None}}, "profile.name"),
({"profile": {"plan": "pro"}}, "profile.plan"),
({"focus": "x"}, "focus"),
({"focus": None}, "focus"),
({"unit": "furlongs"}, "unit"),
({"role": "admin"}, "role"),
({"private_videos": None}, "private_videos"),
({"plan": "pro"}, "plan"),
({"email": "new@example.com"}, "email"),
])
async def test_update_me_validation(client, patch, field):
account = await register(client)
response = await client.patch("/v1/me", headers=account["headers"], json=patch)
assert response.status_code == 400, response.text
error = response.json()["error"]
assert error["code"] == "VALIDATION"
assert field in error["fields"], error
async def test_role_locked_by_session(client):
account = await register(client)
await _make_session(account["user"]["id"])
response = await client.patch("/v1/me", headers=account["headers"], json={"role": "coach"})
assert response.status_code == 409
assert response.json()["error"]["code"] == "ROLE_LOCKED"
async def test_role_locked_by_team_membership_and_coaching(client):
coach = await register(client, role="coach")
team_id = await _make_team(coach["user"]["id"])
player = await register(client)
await _sql("UPDATE accounts SET team_id = :team WHERE id = :id", team=team_id, id=player["user"]["id"])
for account, role in ((coach, "player"), (player, "coach")):
response = await client.patch("/v1/me", headers=account["headers"], json={"role": role})
assert response.status_code == 409
assert response.json()["error"]["code"] == "ROLE_LOCKED"
async def test_update_me_requires_token(client):
response = await client.patch("/v1/me", json={"focus": "h"})
assert response.status_code == 401
# B5 DELETE /me
async def test_delete_me_removes_account_and_media(client):
account = await register(client)
owner = account["user"]["id"]
key = f"videos/{owner}/clip.mp4"
s3 = _s3()
s3.put_object(Bucket="test-media", Key=key, Body=b"video")
await _make_upload(owner, key)
await _make_session(owner)
other = await register(client)
other_key = f"videos/{other['user']['id']}/clip.mp4"
s3.put_object(Bucket="test-media", Key=other_key, Body=b"video")
await _make_upload(other["user"]["id"], other_key)
response = await client.delete("/v1/me", headers=account["headers"])
assert response.status_code == 204
with pytest.raises(ClientError):
s3.head_object(Bucket="test-media", Key=key)
s3.head_object(Bucket="test-media", Key=other_key)
assert (await _sql("SELECT count(*) FROM accounts WHERE id = :id", id=owner)).scalar() == 0
assert (await _sql("SELECT count(*) FROM sessions WHERE owner_id = :id", id=owner)).scalar() == 0
assert (await client.get("/v1/me", headers=account["headers"])).status_code == 401
login = await client.post("/v1/auth/login", json={"email": account["user"]["email"], "password": "x" * 8})
assert login.status_code == 401
async def test_delete_coach_frees_players(client):
coach = await register(client, role="coach")
team_id = await _make_team(coach["user"]["id"])
player = await register(client)
await _sql("UPDATE accounts SET team_id = :team WHERE id = :id", team=team_id, id=player["user"]["id"])
assert (await client.delete("/v1/me", headers=coach["headers"])).status_code == 204
me = (await client.get("/v1/me", headers=player["headers"])).json()
assert me["team"] is None and me["user"]["team_code"] is None
async def test_delete_me_requires_token(client):
response = await client.delete("/v1/me")
assert response.status_code == 401
|