Files
mtusi2026lab2/student-tests/test_rollback.py
T

61 lines
1.8 KiB
Python

import asyncio
import base64
import uuid
import httpx
import pytest
BASE = "http://127.0.0.1:8080"
PASSWORD = "Example-only-not-a-real-secret-123"
async def _create_user(c, name):
return await c.post(
"/api/v1/users",
json={"username": name, "display_name": name, "password": PASSWORD},
)
async def _login(c, name):
cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
r = await c.post(
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"}
)
return r.json()["token"]
@pytest.mark.asyncio
async def test_duplicate_username_race():
async with httpx.AsyncClient(base_url=BASE, timeout=10) as c:
name = f"dup_{uuid.uuid4().hex[:8]}"
r1, r2 = await asyncio.gather(_create_user(c, name), _create_user(c, name))
codes = sorted([r1.status_code, r2.status_code])
assert codes == [201, 409], codes
@pytest.mark.asyncio
async def test_chat_with_unknown_member_rolls_back():
async with httpx.AsyncClient(base_url=BASE, timeout=10) as c:
name = f"cb_{uuid.uuid4().hex[:8]}"
me = (await _create_user(c, name)).json()
tok = await _login(c, name)
r = await c.post(
"/api/v1/chats",
json={"title": "x", "member_ids": [me["id"], str(uuid.uuid4())]},
headers={"Authorization": f"Bearer {tok}"},
)
assert r.status_code == 404
@pytest.mark.asyncio
async def test_message_to_missing_chat():
async with httpx.AsyncClient(base_url=BASE, timeout=10) as c:
name = f"mc_{uuid.uuid4().hex[:8]}"
await _create_user(c, name)
tok = await _login(c, name)
r = await c.post(
f"/api/v1/chats/{uuid.uuid4()}/messages",
json={"text": "hi"},
headers={"Authorization": f"Bearer {tok}"},
)
assert r.status_code == 404