forked from mtusi2026/mtusi2026lab2
rollback-тесты на urllib из-за нестабильности httpx через docker-proxy на win
This commit is contained in:
+5
-3
@@ -16,7 +16,7 @@ SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
def _prehash(password: str) -> bytes:
|
||||
# bcrypt работает с ≤72 байт, SHA-256 даёт 32 байта и снимает ограничение
|
||||
return hashlib.sha256(password.encode("utf-8")).digest()
|
||||
return hashlib.sha256(password.encode("utf-8")).hexdigest().encode("ascii")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
@@ -72,7 +72,9 @@ async def revoke_current_session(authorization: str, db: AsyncSession) -> None:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise _unauthorized_bearer()
|
||||
token = authorization[7:]
|
||||
await db.execute(
|
||||
result = await db.execute(
|
||||
delete(SessionRow).where(SessionRow.token_hash == hash_token(token))
|
||||
)
|
||||
await db.commit()
|
||||
await db.commit()
|
||||
if result.rowcount == 0:
|
||||
raise _unauthorized_bearer()
|
||||
+21
-13
@@ -10,20 +10,28 @@ from ..db.models import Chat, ChatMember, User
|
||||
async def create_atomic(
|
||||
db: AsyncSession, title: str, member_ids: list[UUID]
|
||||
) -> Chat:
|
||||
async with db.begin():
|
||||
found = (
|
||||
(await db.execute(select(User.id).where(User.id.in_(member_ids))))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
if len(set(found)) != len(set(member_ids)):
|
||||
raise ValueError("member_not_found")
|
||||
# проверка всех участников
|
||||
found = (
|
||||
(await db.execute(select(User.id).where(User.id.in_(member_ids))))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
if len(set(found)) != len(set(member_ids)):
|
||||
await db.rollback()
|
||||
raise ValueError("member_not_found")
|
||||
|
||||
chat = Chat(title=title)
|
||||
db.add(chat)
|
||||
await db.flush()
|
||||
for uid in member_ids:
|
||||
db.add(ChatMember(chat_id=chat.id, user_id=uid))
|
||||
chat = Chat(title=title)
|
||||
db.add(chat)
|
||||
await db.flush() # получить chat.id
|
||||
|
||||
for uid in member_ids:
|
||||
db.add(ChatMember(chat_id=chat.id, user_id=uid))
|
||||
|
||||
try:
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
await db.refresh(chat)
|
||||
return chat
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
docker compose restart api
|
||||
docker compose restart postgres
|
||||
docker compose restart redis
|
||||
@@ -1,61 +1,86 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
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},
|
||||
def _post(path, body, token=None):
|
||||
h = {"Content-Type": "application/json", "Accept": "application/json"}
|
||||
if token:
|
||||
h["Authorization"] = f"Bearer {token}"
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
req = urllib.request.Request(BASE + path, data=data, method="POST", headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read()
|
||||
try:
|
||||
return e.code, json.loads(payload) if payload else None
|
||||
except ValueError:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def _post_basic(path, username, password):
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
req = urllib.request.Request(
|
||||
BASE + path, method="POST",
|
||||
headers={"Authorization": f"Basic {cred}", "Accept": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
|
||||
|
||||
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"]
|
||||
def _create_user(name):
|
||||
return _post("/api/v1/users", {
|
||||
"username": name, "display_name": name, "password": PASSWORD,
|
||||
})
|
||||
|
||||
|
||||
@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
|
||||
def _login(name):
|
||||
_, body = _post_basic("/api/v1/auth/sessions", name, PASSWORD)
|
||||
return body["token"]
|
||||
|
||||
|
||||
@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
|
||||
def test_duplicate_username_race():
|
||||
name = f"dup_{uuid.uuid4().hex[:8]}"
|
||||
|
||||
import threading
|
||||
results = [None, None]
|
||||
|
||||
def worker(i):
|
||||
results[i] = _create_user(name)
|
||||
|
||||
t1 = threading.Thread(target=worker, args=(0,))
|
||||
t2 = threading.Thread(target=worker, args=(1,))
|
||||
t1.start(); t2.start()
|
||||
t1.join(); t2.join()
|
||||
|
||||
codes = sorted([results[0][0], results[1][0]])
|
||||
assert codes == [201, 409], codes
|
||||
|
||||
|
||||
@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
|
||||
def test_chat_with_unknown_member_rolls_back():
|
||||
name = f"cb_{uuid.uuid4().hex[:8]}"
|
||||
s, me = _create_user(name)
|
||||
assert s == 201, me
|
||||
tok = _login(name)
|
||||
s, _ = _post("/api/v1/chats", {
|
||||
"title": "x", "member_ids": [me["id"], str(uuid.uuid4())],
|
||||
}, token=tok)
|
||||
assert s == 404
|
||||
|
||||
|
||||
def test_message_to_missing_chat():
|
||||
name = f"mc_{uuid.uuid4().hex[:8]}"
|
||||
_create_user(name)
|
||||
tok = _login(name)
|
||||
s, _ = _post(f"/api/v1/chats/{uuid.uuid4()}/messages", {"text": "hi"}, token=tok)
|
||||
assert s == 404
|
||||
Reference in New Issue
Block a user