rollback-тесты на urllib из-за нестабильности httpx через docker-proxy на win

This commit is contained in:
2026-10-01 02:57:49 +03:00
parent f3a6f7a62f
commit 14ec627341
4 changed files with 97 additions and 58 deletions
+67 -42
View File
@@ -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