test: строгие тесты lab3 — идемпотентность, балансировка, отказы реплик

- test_idempotency: точные коды и тела повторов через разные реплики, 24
  одновременных запроса с одним ключом -> ровно одно сообщение и одна строка
  ключа в БД, 409 при другом body, scope user+chat+key, 404 постороннему,
  откат после сбоя на втором INSERT (триггер, n_tup_ins), неопределённый
  POST (клиентский timeout) и lock_timeout с повтором тем же ключом.
- test_balancing: X-Instance-Id = реальные контейнеры, нет sticky,
  LB исключает живую, но неготовую реплику (pg_hba reject), graceful stop
  каждой реплики под нагрузкой без единой ошибки, SIGKILL — ограниченные
  ошибки и восстановление, полный restart и scale up/down без рестарта LB,
  политика compose (лимиты, порты, secrets, digest), миграции один раз.
- Входы из замечаний к чужим PR: курсоры с []/{}/числами/пустые/пробел,
  байт FF, TEXT/text, дубли ключей, Bearer é, UUID в разном регистре, тело
  при входе, пароль "я:"*64. Тесты lab2 переведены на Idempotency-Key и LB;
  все отказы восстанавливаются в finally и ждут UP всех реплик в HAProxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Bodanyuk
2026-10-16 13:32:13 +03:00
co-authored by Claude Opus 5.5
parent 3f12698676
commit 78b95acabf
8 changed files with 848 additions and 30 deletions
+105 -2
View File
@@ -108,7 +108,7 @@ def test_unicode_limits_are_code_points_and_nul_is_stored(api):
assert chat["title"] == "T\u0000itle"
assert api.send(actor, chat, "hello\u0000world")["text"] == "hello\u0000world"
assert api.send(actor, chat, "🙂" * 4000)["text"] == "🙂" * 4000
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=actor["token"], json_body={"text": "я" * 4001})
api.post_message(actor, chat, {"text": "я" * 4001}, 400)
texts = [m["text"] for m in api.history(actor, chat, 100)[0]]
assert texts == ["hello\u0000world", "🙂" * 4000]
@@ -136,7 +136,7 @@ def test_foreign_chat_is_indistinguishable_from_missing(api):
base = f"/api/v1/chats/{chat_id}"
errors = [api.call("GET", base, 404, token=eve["token"]).json(),
api.call("GET", base + "/messages", 404, token=eve["token"]).json(),
api.call("POST", base + "/messages", 404, token=eve["token"], json_body={"text": "чужое"}).json(),
api.call("POST", base + "/messages", 404, token=eve["token"], json_body={"text": "чужое"}, headers={"Idempotency-Key": "k1"}).json(),
api.call("GET", base + "/messages?cursor=garbage", 404, token=eve["token"]).json()]
assert len({e["error"]["message"] for e in errors}) == 1
api.call("GET", "/api/v1/chats/not-a-uuid", 401)
@@ -199,3 +199,106 @@ def test_read_after_write(api):
message = api.send(alice, chat, f"m{i}")
last = api.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"]).json()["items"][-1]
assert last == message
# ================================================================== lab 3: inputs found by the reviewer in other PRs
def b64(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def bad_cursors(owner_id: str) -> list[str]:
"""Wrong types/values inside the cursor, empty and whitespace cursors, out-of-range time."""
good_uuid = str(uuid.uuid4())
return ["", " ", "%20", "garbage", b64(b"[]"), b64(b"{}"), b64(b"123"), b64(b"false"), b64(b"null"),
b64(b'{"created_at":1,"id":1}'), b64(b'{"created_at":null,"id":"x"}'),
b64(f"v1|m|{owner_id}|1|1".encode()), b64(f"v1|c|{owner_id}|1|1".encode()),
b64(f"v1|m|{owner_id}|abc|{good_uuid}".encode()), b64(f"v1|m|{owner_id}|-1|{good_uuid}".encode()),
b64(f"v1|m|{owner_id}|9223372036854775807|{good_uuid}".encode()),
b64(f"v1|c|{owner_id}|9223372036854775807|{good_uuid}".encode()),
b64(f"v1|m|{owner_id}|1|{good_uuid.upper()}".encode()), b64(f"v2|m|{owner_id}|1|{good_uuid}".encode())]
def test_malformed_cursor_values_are_400_on_both_lists(api):
alice = api.user("cur")
chat = api.chat(alice)
for cursor in bad_cursors(chat["id"]) + bad_cursors(alice["id"]):
quoted = cursor if cursor in ("", "%20") else cursor.replace(" ", "%20")
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
error = api.call("GET", f"{path}?cursor={quoted}", 400, token=alice["token"]).json()
assert error["error"]["code"] == "invalid_request", (path, cursor)
@pytest.mark.parametrize("raw", [b"\xff", b'{"text":"first","TEXT":"second"}', b'{"text":"a","text":"b"}',
b'{"text":123}', b'{"text":"valid"}}', b'{"text":"valid"}]', b'{"text":"x"} {}',
b'{"text":"x","sender_id":"11111111-1111-4111-8111-111111111111"}',
b'{"text":"x","attachment_ids":null}', b'{"text":"x","attachment_ids":["nope"]}',
b'{"text":" \n\t "}'])
def test_bad_message_body_is_400_and_nothing_is_stored(api, raw):
alice = api.user("body")
chat = api.chat(alice)
error = api.post_message(alice, chat, None, 400, raw=raw).json()
assert error["error"]["code"] == "invalid_request"
assert api.history(alice, chat, 100)[0] == []
def test_ff_byte_body_on_registration_is_contract_error(api):
response = api.call("POST", "/api/v1/users", 400, raw=b"\xff", headers={"Content-Type": "application/json"})
assert response.json()["error"]["request_id"] == response.headers["x-request-id"]
def test_text_is_stored_verbatim_and_length_counts_raw_text(api):
alice = api.user("verbatim")
chat = api.chat(alice)
padded = " строка\nс пробелами "
assert api.send(alice, chat, padded)["text"] == padded
api.post_message(alice, chat, {"text": " " + "a" * 4000}, 400) # 4001 code points before any trimming
assert [m["text"] for m in api.history(alice, chat, 100)[0]] == [padded]
def test_unknown_attachment_ids_are_404(api):
alice = api.user("att")
chat = api.chat(alice)
api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404)
api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())] * 2}, 400) # duplicates
assert api.history(alice, chat, 100)[0] == []
def test_member_ids_are_compared_as_uuids_not_strings(api):
alice, bob = api.user("case"), api.user("case")
api.call("POST", "/api/v1/chats", 400, token=alice["token"],
json_body={"title": "x", "member_ids": [alice["id"], alice["id"].upper()]})
api.call("POST", "/api/v1/chats", 400, token=alice["token"],
json_body={"title": "x", "member_ids": [alice["id"], bob["id"]], "id": str(uuid.uuid4())})
chat = api.call("POST", "/api/v1/chats", 201, token=alice["token"],
json_body={"title": "x", "member_ids": [alice["id"].upper(), bob["id"]]}, schema="Chat").json()
assert chat["member_ids"] == [alice["id"], bob["id"]]
@pytest.mark.parametrize("header", ["Bearer é", "Bearer .", "Bearer a b", "Bearer " + "é" * 43, "bearer\t" + "a" * 43])
def test_non_ascii_or_garbage_bearer_is_401_not_500(api, header):
api.call("GET", "/api/v1/users/me", 401, headers={"Authorization": header.encode("utf-8")})
def test_login_with_a_body_is_rejected(api):
actor = api.register("login_body")
auth = {"Authorization": basic(actor["username"], actor["password"])}
api.call("POST", "/api/v1/auth/sessions", 400, raw=b'{"extra":1}', headers={**auth, "Content-Type": "application/json"})
api.call("POST", "/api/v1/auth/sessions", 400, raw=b"x", headers=auth)
api.call("POST", "/api/v1/auth/sessions", 201, headers=auth, schema="Session")
def test_password_range_is_12_to_128_code_points(api):
api.call("POST", "/api/v1/users", 400, json_body={"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "x", "password": "a"})
actor = api.user("pw128", password="я:" * 64)
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
def test_every_api_response_carries_instance_and_request_id(api):
"""X-Instance-Id also on 404 of unknown routes, 405, 401, 400 and health (Api.call asserts it)."""
api.call("GET", "/health/live", 200)
api.call("GET", "/health/ready", 200)
api.call("GET", "/no/such/route", 404)
api.call("PUT", "/api/v1/users", 405)
api.call("GET", "/api/v1/users/me", 401)
response = api.call("GET", "/api/v1/users/me", 401, headers={"X-Request-Id": "client-supplied.id-1"})
assert response.headers["x-request-id"] == "client-supplied.id-1" # one id from LB log to API log