Перенес основы lab3 в lab4
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""Additional Lab3 contract checks against the running stack.
|
||||
|
||||
Only synthetic data are used. --database-checks additionally expires one key
|
||||
created by this test using local Compose psql, to avoid waiting 24 hours.
|
||||
"""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return subprocess.run([
|
||||
"docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-A", "-t",
|
||||
"-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", "-c", statement,
|
||||
], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8084")
|
||||
parser.add_argument("--database-checks", action="store_true")
|
||||
args = parser.parse_args()
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = uuid.uuid4().hex
|
||||
text = "Привет, мир"
|
||||
first = c.message(alice, chat, text, key=key)["json"]
|
||||
raw = (" " + json.dumps({"text": text}, ensure_ascii=True, indent=2) + "\n").encode()
|
||||
replay = c.call("POST", path, 201, actor=alice, raw=raw,
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": key},
|
||||
schema="Message")["json"]
|
||||
check(first == replay, "Equivalent JSON changed replay result")
|
||||
for invalid in ["", "a b", "\xe9", "a" * 129]:
|
||||
c.call("POST", path, 400, actor=alice, body={"text": text},
|
||||
headers={"Idempotency-Key": invalid})
|
||||
c.message(alice, chat, "Maximum length key", key="a" * 128)
|
||||
print("PASS: decoded JSON equality; invalid keys -> 400; 128-character key accepted")
|
||||
|
||||
by_bob = c.message(bob, chat, text, key=key)["json"]
|
||||
check(by_bob["id"] != first["id"], "Different users share an idempotency result")
|
||||
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Scope test", "member_ids": [alice["id"]]},
|
||||
schema="Chat")["json"]
|
||||
by_chat = c.message(alice, other_chat, text, key=key)["json"]
|
||||
check(by_chat["id"] != first["id"], "Different chats share an idempotency result")
|
||||
c.call("POST", path, 404, actor=eve, body={"text": text}, headers={"Idempotency-Key": key})
|
||||
print("PASS: key scope is per user/chat; unauthorized chat replay -> 404")
|
||||
|
||||
race_key = uuid.uuid4().hex
|
||||
def conflicting(index):
|
||||
local = Client(args.base_url)
|
||||
return local.call("POST", path, [201, 409], actor=alice,
|
||||
body={"text": "race-" + str(index % 2)},
|
||||
headers={"Idempotency-Key": race_key}, schema=None)
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(conflicting, range(16)))
|
||||
check(sum(item["status"] == 201 for item in results) == 8, "Wrong number of winning replays")
|
||||
check(sum(item["status"] == 409 for item in results) == 8, "Wrong number of conflicts")
|
||||
check(len({item["headers"]["X-Instance-Id"] for item in results}) >= 2,
|
||||
"Conflicting race did not span replicas")
|
||||
history = c.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"]["items"]
|
||||
check(sum(item["text"].startswith("race-") for item in history) == 1, "Conflicting race created duplicates")
|
||||
print("PASS: concurrent different bodies -> eight 201 and eight 409; one new message")
|
||||
|
||||
if args.database_checks:
|
||||
# UUID conversion prevents server-returned IDs from becoming SQL syntax.
|
||||
actor_id = str(uuid.UUID(alice["id"]))
|
||||
chat_id = str(uuid.UUID(chat["id"]))
|
||||
where = f"user_id='{actor_id}' AND chat_id='{chat_id}' AND key='{key}'"
|
||||
check(sql("SELECT count(*) FROM message_keys WHERE " + where +
|
||||
" AND expires_at>clock_timestamp()+INTERVAL '23 hours'") == "1", "Key TTL too short")
|
||||
sql("UPDATE message_keys SET expires_at=clock_timestamp()-INTERVAL '1 second' WHERE " + where)
|
||||
after_expiry = c.message(alice, chat, "New operation after expiry", key=key)["json"]
|
||||
check(after_expiry["id"] != first["id"], "Expired key was not reusable")
|
||||
check(c.message(alice, chat, "New operation after expiry", key=key)["json"] == after_expiry,
|
||||
"New key cycle is not idempotent")
|
||||
check(sql("SELECT count(*) FROM message_keys WHERE " + where) == "1", "Key replacement duplicated row")
|
||||
print("PASS: TTL persisted; simulated expiry permits a new idempotent operation")
|
||||
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
c.call("POST", path, 401, actor=alice, body={"text": text}, headers={"Idempotency-Key": key})
|
||||
print("PASS: revoked session cannot replay a previous operation")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user