Files
mtusi2026lab3-fork/unit-tests/test_mr_regressions.py
T
2026-11-02 20:05:33 +03:00

152 lines
6.7 KiB
Python

"""Проверки отзыва и cursor без внешних сервисов; SQL-путь проверяется отдельно."""
from types import SimpleNamespace
from unittest.mock import AsyncMock
import uuid
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.exc import OperationalError
from app.auth import current_user, get_session
from app.config import Settings
from app.cursor import decode_cursor, encode_cursor
from app.main import create_app
from app.models import User
from app.timeutil import EPOCH, MAX_TIMESTAMP_MICROS, from_micros, to_micros
USER_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
CHAT_ID = "00000000-0000-0000-0000-000000000002"
PROFILE = {"id": str(USER_ID), "username": "alice", "display_name": "Alice", "created_at": EPOCH.isoformat()}
HEADERS = {"Authorization": "Bearer " + "A" * 43}
@pytest.fixture
def app_client():
"""Приложение с подменённой сессией БД, без запуска lifespan."""
settings = Settings.from_env({"DATABASE_URL": "postgresql+asyncpg://test:test@localhost/test"})
app = create_app(settings)
session = AsyncMock()
async def session_override():
yield session
app.dependency_overrides[get_session] = session_override
app.state.cache = SimpleNamespace(get=AsyncMock(return_value=PROFILE), put=AsyncMock())
client = TestClient(app, raise_server_exceptions=False)
yield client, session
client.close()
@pytest.mark.parametrize("path, method", [
("/api/v1/users/me", "GET"),
(f"/api/v1/chats/{CHAT_ID}/messages", "POST"),
("/api/v1/auth/sessions/current", "DELETE"),
])
def test_stale_positive_cache_never_authorizes_revoked_token(app_client, monkeypatch, path, method):
client, session = app_client
check = AsyncMock(return_value=False)
monkeypatch.setattr("app.crud.session_is_active", check)
write = AsyncMock()
monkeypatch.setattr("app.crud.create_message_idempotent", write)
reply = client.request(method, path, headers=HEADERS)
assert reply.status_code == 401
assert reply.json()["error"]["code"] == "unauthorized"
assert reply.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
check.assert_awaited_once()
write.assert_not_awaited()
def test_valid_cache_hit_checks_session_without_loading_user(app_client, monkeypatch):
client, session = app_client
check = AsyncMock(return_value=True)
load = AsyncMock()
monkeypatch.setattr("app.crud.session_is_active", check)
monkeypatch.setattr("app.crud.get_user_by_token", load)
reply = client.get("/api/v1/users/me", headers=HEADERS)
assert reply.status_code == 200
assert reply.json()["id"] == str(USER_ID)
check.assert_awaited_once()
load.assert_not_awaited()
def test_database_failure_on_positive_cache_hit_is_503(app_client, monkeypatch):
client, session = app_client
monkeypatch.setattr("app.crud.session_is_active", AsyncMock(side_effect=OperationalError("", {}, Exception())))
reply = client.get("/api/v1/users/me", headers=HEADERS)
assert reply.status_code == 503
assert reply.json()["error"]["code"] == "unavailable"
@pytest.mark.parametrize("stamp", [-1, MAX_TIMESTAMP_MICROS + 1, 10**30, True, 1.5, "1", None])
@pytest.mark.parametrize("resource", ["messages", "chats"])
def test_cursor_timestamp_is_rejected_through_http(app_client, monkeypatch, stamp, resource):
client, session = app_client
user = User(id=USER_ID)
client.app.dependency_overrides[current_user] = lambda: user
monkeypatch.setattr("app.crud.get_chat_for_member", AsyncMock(return_value=SimpleNamespace(id=uuid.UUID(CHAT_ID))))
scope = "messages:" + CHAT_ID if resource == "messages" else "chats:" + str(USER_ID)
path = f"/api/v1/chats/{CHAT_ID}/messages" if resource == "messages" else "/api/v1/chats"
reply = client.get(path, params={"cursor": encode_cursor(scope, (stamp, CHAT_ID))})
assert reply.status_code == 400
assert reply.json()["error"]["code"] == "invalid_request"
assert reply.json()["error"]["request_id"] == reply.headers["X-Request-Id"]
@pytest.mark.parametrize("stamp", [0, MAX_TIMESTAMP_MICROS])
def test_timestamp_boundaries_roundtrip(stamp):
key = decode_cursor(encode_cursor("scope", (stamp, CHAT_ID)), "scope")
assert key == (stamp, CHAT_ID)
assert to_micros(from_micros(key[0])) == stamp
@pytest.mark.parametrize("key", [None, "", "bad key", "x" * 129, "a?b", "a,b"])
def test_message_key_validation(app_client, monkeypatch, key):
client, session = app_client
client.app.dependency_overrides[current_user] = lambda: User(id=USER_ID)
monkeypatch.setattr("app.crud.get_chat_for_member", AsyncMock(return_value=SimpleNamespace(id=uuid.UUID(CHAT_ID))))
send = AsyncMock()
monkeypatch.setattr("app.crud.create_message_idempotent", send)
headers = {} if key is None else {"Idempotency-Key": key}
reply = client.post(f"/api/v1/chats/{CHAT_ID}/messages", json={"text": "hi"}, headers=headers)
assert reply.status_code == 400
send.assert_not_awaited()
def test_message_normalization_and_conflict(app_client, monkeypatch):
from app.crud import IdempotencyConflict
client, session = app_client
client.app.dependency_overrides[current_user] = lambda: User(id=USER_ID)
monkeypatch.setattr("app.crud.get_chat_for_member", AsyncMock(return_value=SimpleNamespace(id=uuid.UUID(CHAT_ID))))
send = AsyncMock(side_effect=IdempotencyConflict())
monkeypatch.setattr("app.crud.create_message_idempotent", send)
for body in ({"text": "hi"}, {"attachment_ids": [], "text": "hi"}):
reply = client.post(f"/api/v1/chats/{CHAT_ID}/messages", json=body, headers={"Idempotency-Key": "same"})
assert reply.status_code == 409
assert reply.json()["error"]["code"] == "conflict"
assert send.await_args_list[0] == send.await_args_list[1]
@pytest.mark.parametrize("path", ["/health/live", "/missing", "/api/v1/users/me"])
def test_instance_header_matches_process_on_all_responses(app_client, path):
client, session = app_client
reply = client.get(path)
assert reply.headers["X-Instance-Id"] == client.app.state.instance_id
assert client.get(path).headers["X-Instance-Id"] == reply.headers["X-Instance-Id"]
def test_instance_alias_changes_between_applications():
settings = Settings.from_env({"DATABASE_URL": "postgresql+asyncpg://t:t@localhost/t"})
assert create_app(settings).state.instance_id != create_app(settings).state.instance_id
def test_sigterm_drops_readiness_and_requests_graceful_exit():
import signal
import uvicorn
from app.__main__ import GracefulServer
app = SimpleNamespace(state=SimpleNamespace(ready=True))
server = GracefulServer(uvicorn.Config(app))
server.handle_exit(signal.SIGTERM, None)
assert app.state.ready is False
assert server.should_exit is True