forked from mtusi2026/mtusi2026lab2
ЛР 2: автотесты уровня 4, обработка отказа БД
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
test_chat_creation_rolls_back (test_level4.Level4.test_chat_creation_rolls_back) ... /opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 400: 'Bad Request'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
ok
|
||||
test_logout_revokes_session_and_cache (test_level4.Level4.test_logout_revokes_session_and_cache) ... /opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 401: 'Unauthorized'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
ok
|
||||
test_postgres_down_returns_bounded_error (test_level4.Level4.test_postgres_down_returns_bounded_error) ... /opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 503: 'Service Unavailable'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
/opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 401: 'Unauthorized'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
/opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 503: 'Service Unavailable'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
ok
|
||||
test_register_race_same_username (test_level4.Level4.test_register_race_same_username) ... /opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 409: 'Conflict'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
ok
|
||||
test_valkey_down_falls_back_to_postgres (test_level4.Level4.test_valkey_down_falls_back_to_postgres) ... /opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 401: 'Unauthorized'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
ok
|
||||
test_wrong_password (test_level4.Level4.test_wrong_password) ... /opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 401: 'Unauthorized'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
ok
|
||||
test_x_user_id_gives_no_access (test_level4.Level4.test_x_user_id_gives_no_access) ... ok
|
||||
test_zz_session_expiry (test_level4.Level4.test_zz_session_expiry) ... /opt/homebrew/Cellar/python@3.14/3.14.0_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/tempfile.py:484: ResourceWarning: Implicitly cleaning up <HTTPError 401: 'Unauthorized'>
|
||||
_warnings.warn(self.warn_message, ResourceWarning)
|
||||
ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 8 tests in 12.946s
|
||||
|
||||
OK
|
||||
+1
-1
@@ -95,7 +95,7 @@ async def dependency_unavailable_handler(request: Request, exc: Exception):
|
||||
return make_error_response(503, "unavailable", "Service temporarily unavailable", _req_id(request))
|
||||
|
||||
|
||||
for _exc in (asyncpg.PostgresError, asyncpg.InterfaceError, ConnectionError, asyncio.TimeoutError):
|
||||
for _exc in (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, asyncio.TimeoutError):
|
||||
app.add_exception_handler(_exc, dependency_unavailable_handler)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Проверки уровня 4. Нужен запущенный стенд (docker compose up -d --build).
|
||||
Тесты отказов сами останавливают и запускают valkey/postgres/api, volumes не удаляются.
|
||||
Запуск: python3 -m unittest discover -s student_tests -p "test_level4.py" -v
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PASSWORD = "correct-horse-battery"
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = {"Content-Type": "application/json"} if body is not None else {}
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
raw = resp.read()
|
||||
return resp.status, (json.loads(raw) if raw else None)
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw = exc.read()
|
||||
try:
|
||||
return exc.code, (json.loads(raw) if raw else None)
|
||||
except ValueError:
|
||||
return exc.code, None
|
||||
|
||||
|
||||
def register(username=None):
|
||||
username = username or "u" + uuid.uuid4().hex[:12]
|
||||
status, user = call("POST", "/api/v1/users",
|
||||
{"username": username, "display_name": "Test", "password": PASSWORD})
|
||||
assert status == 201, status
|
||||
return user
|
||||
|
||||
|
||||
def login(username, password=PASSWORD):
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": "Bearer " + token}
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
full_env = dict(os.environ)
|
||||
full_env.update(env or {})
|
||||
result = subprocess.run(["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT, env=full_env, check=True, capture_output=True, text=True)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def wait_ready(timeout=90):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if call("GET", "/health/ready")[0] == 200:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError("API did not become ready")
|
||||
|
||||
|
||||
def new_session():
|
||||
user = register()
|
||||
status, session = login(user["username"])
|
||||
assert status == 201
|
||||
return user, session["token"]
|
||||
|
||||
|
||||
class Level4(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
wait_ready()
|
||||
|
||||
def test_wrong_password(self):
|
||||
user = register()
|
||||
status, body = login(user["username"], "definitely-wrong-password")
|
||||
self.assertEqual(status, 401)
|
||||
self.assertEqual(body["error"]["code"], "unauthorized")
|
||||
status, _ = login("no_such_user_" + uuid.uuid4().hex[:8])
|
||||
self.assertEqual(status, 401)
|
||||
|
||||
def test_logout_revokes_session_and_cache(self):
|
||||
_, token = new_session()
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200) # прогрев кэша
|
||||
self.assertEqual(call("DELETE", "/api/v1/auth/sessions/current", headers=bearer(token))[0], 204)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 401)
|
||||
self.assertEqual(call("DELETE", "/api/v1/auth/sessions/current", headers=bearer(token))[0], 401)
|
||||
|
||||
def test_x_user_id_gives_no_access(self):
|
||||
user = register()
|
||||
status, _ = call("GET", "/api/v1/users/me", headers={"X-User-Id": user["id"]})
|
||||
self.assertEqual(status, 401)
|
||||
|
||||
def test_register_race_same_username(self):
|
||||
username = "race" + uuid.uuid4().hex[:10]
|
||||
results = []
|
||||
|
||||
def worker():
|
||||
status, _ = call("POST", "/api/v1/users",
|
||||
{"username": username, "display_name": "Race", "password": PASSWORD})
|
||||
results.append(status)
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(10)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
self.assertEqual(results.count(201), 1, results)
|
||||
self.assertEqual(results.count(409), 9, results)
|
||||
|
||||
def test_chat_creation_rolls_back(self):
|
||||
user, token = new_session()
|
||||
title = "rollback-" + uuid.uuid4().hex
|
||||
status, _ = call("POST", "/api/v1/chats",
|
||||
{"title": title, "member_ids": [user["id"], str(uuid.uuid4())]},
|
||||
headers=bearer(token))
|
||||
self.assertEqual(status, 400)
|
||||
# Проверяем саму БД: после отката не осталось ни чата, ни участников.
|
||||
count = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-tAc", f"SELECT count(*) FROM chats WHERE title = '{title}'").strip()
|
||||
self.assertEqual(count, "0")
|
||||
|
||||
def test_valkey_down_falls_back_to_postgres(self):
|
||||
user, token = new_session()
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
self.assertEqual(login(user["username"])[0], 201)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me")[0], 401)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer("x" * 43))[0], 401)
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
|
||||
def test_postgres_down_returns_bounded_error(self):
|
||||
compose("stop", "postgres")
|
||||
try:
|
||||
status, body = call("GET", "/health/ready")
|
||||
self.assertEqual(status, 503)
|
||||
self.assertEqual(body["error"]["code"], "unavailable")
|
||||
# неизвестный токен нельзя ни подтвердить, ни отвергнуть без БД: 503, не 200
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer("y" * 43))[0], 503)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me")[0], 401) # аноним не доверенный
|
||||
self.assertEqual(call("POST", "/api/v1/users",
|
||||
{"username": "down" + uuid.uuid4().hex[:8], "display_name": "X",
|
||||
"password": PASSWORD})[0], 503)
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
wait_ready()
|
||||
|
||||
def test_zz_session_expiry(self):
|
||||
compose("up", "-d", "api", env={"SESSION_TTL_SECONDS": "2"})
|
||||
try:
|
||||
wait_ready()
|
||||
_, token = new_session()
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
time.sleep(3.5)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 401)
|
||||
finally:
|
||||
compose("up", "-d", "api") # обратно к TTL из .env
|
||||
wait_ready()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user