Files
mtusi2026lab5/student-tests/test_cluster.py
T

138 lines
5.9 KiB
Python

import json
from concurrent.futures import ThreadPoolExecutor
from dataclasses import replace
from uuid import uuid4
import psycopg
import pytest
from fastapi.testclient import TestClient
from test_api import error, headers
from messenger.app import create_app
@pytest.mark.parametrize("key", [None, "", "a b", "/", "a" * 129])
def test_message_key_required(client, actors, room, key):
h = {"Authorization": "Bearer " + actors[0]["token"]}
if key is not None:
h["Idempotency-Key"] = key
error(
client.post(
f"/api/v1/chats/{room['id']}/messages", headers=h, json={"text": "key validation"}
),
400,
"invalid_request",
)
def test_replay_scope_conflict_and_fresh_authorization(client, actors, room):
path = f"/api/v1/chats/{room['id']}/messages"
key = "Scope.Key:123"
h = {**headers(actors[0]), "Idempotency-Key": key}
first = client.post(path, headers=h, json={"text": "exact whitespace \n"})
assert first.status_code == 201
repeat = client.post(
path,
headers={**h, "Content-Type": "application/json"},
content=json.dumps({"text": "exact whitespace \n"}, indent=3),
)
assert repeat.status_code == 201 and repeat.json() == first.json()
error(client.post(path, headers=h, json={"text": "different"}), 409, "conflict")
outsider = {**headers(actors[2]), "Idempotency-Key": key}
error(
client.post(path, headers=outsider, json={"text": "exact whitespace \n"}), 404, "not_found"
)
other_user = {**headers(actors[1]), "Idempotency-Key": key}
own = client.post(path, headers=other_user, json={"text": "another author"})
assert own.status_code == 201 and own.json()["id"] != first.json()["id"]
chat = client.post(
"/api/v1/chats",
headers=headers(actors[0]),
json={"title": "another", "member_ids": [actors[0]["id"]]},
).json()
other_chat = client.post(
f"/api/v1/chats/{chat['id']}/messages", headers=h, json={"text": "different chat"}
)
assert other_chat.status_code == 201 and other_chat.json()["id"] != first.json()["id"]
assert client.delete("/api/v1/auth/sessions/current", headers=h).status_code == 204
error(client.post(path, headers=h, json={"text": "exact whitespace \n"}), 401, "unauthorized")
def test_concurrent_replay_across_independent_apps(client, actors, room, settings):
path = f"/api/v1/chats/{room['id']}/messages"
h = {**headers(actors[0]), "Idempotency-Key": uuid4().hex}
with TestClient(create_app(settings)) as second:
assert second.app.state.instance_id != client.app.state.instance_id
def send(i):
c = client if i % 2 else second
r = c.post(path, headers=h, json={"text": "same concurrent body"})
assert r.status_code == 201
return r.json(), r.headers["X-Instance-Id"]
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(send, range(30)))
assert len({item[0]["id"] for item in results}) == 1
assert len({item[1] for item in results}) == 2
assert len(client.get(path, headers=headers(actors[1])).json()["items"]) == 1
def test_side_effect_and_result_rollback_together(client, actors, room, settings, monkeypatch):
repository = client.app.state.repository
original = repository._save_request
def fail_after_message_insert(*args):
raise RuntimeError("injected between message and result")
monkeypatch.setattr(repository, "_save_request", fail_after_message_insert)
path = f"/api/v1/chats/{room['id']}/messages"
h = {**headers(actors[0]), "Idempotency-Key": uuid4().hex}
error(
client.post(path, headers=h, json={"text": "retry after rollback"}), 500, "internal_error"
)
with psycopg.connect(settings.database_url) as conn:
assert conn.execute("SELECT count(*) FROM messages").fetchone()[0] == 0
assert conn.execute("SELECT count(*) FROM message_requests").fetchone()[0] == 0
monkeypatch.setattr(repository, "_save_request", original)
result = client.post(path, headers=h, json={"text": "retry after rollback"})
assert result.status_code == 201
assert (
client.post(path, headers=h, json={"text": "retry after rollback"}).json() == result.json()
)
def test_expired_key_can_be_reused_without_deleting_old_message(client, actors, room, settings):
path = f"/api/v1/chats/{room['id']}/messages"
h = {**headers(actors[0]), "Idempotency-Key": uuid4().hex}
first = client.post(path, headers=h, json={"text": "old"}).json()
with psycopg.connect(settings.database_url) as conn:
conn.execute(
"UPDATE message_requests SET created_at=clock_timestamp()-interval '2 days', "
"expires_at=clock_timestamp()-interval '1 day'"
)
second = client.post(path, headers=h, json={"text": "new"})
assert second.status_code == 201 and second.json()["id"] != first["id"]
assert len(client.get(path, headers=headers(actors[0])).json()["items"]) == 2
@pytest.mark.parametrize("optimized", [True, False])
def test_read_modes_preserve_public_result(client, actors, room, settings, optimized):
with TestClient(create_app(replace(settings, read_autocommit=optimized))) as c:
c.get("/api/v1/users/me", headers=headers(actors[0]))
pool = c.app.state.repository.pool
before = pool.get_stats().get("requests_num", 0)
response = c.get(f"/api/v1/chats/{room['id']}/messages", headers=headers(actors[0]))
assert response.status_code == 200 and response.json()["items"] == []
assert pool.get_stats()["requests_num"] - before == 3
def test_instance_header_covers_health_errors_and_success(client):
values = [
client.get("/health/live"),
client.get("/health/ready"),
client.get("/api/v1/users/me"),
client.get("/not-a-route"),
]
assert len({r.headers["X-Instance-Id"] for r in values}) == 1
assert all(len(r.headers.get_list("X-Instance-Id")) == 1 for r in values)