baseball-engine / backend /tests /integration /test_accounts.py
github-actions[bot]
Automated Deploy: bc9f9bdebdd9f5ac1fd6eca496428aa61a69a2cc
6437539
Raw History Blame Contribute Delete
10.1 kB
"""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