Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
99 lines
2.9 KiB
Python
99 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Exercise registration races, chat transaction rollback, and migration idempotence."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from urllib.error import HTTPError
|
|
from urllib.request import Request, urlopen
|
|
import uuid
|
|
|
|
from psycopg.errors import ForeignKeyViolation
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
from src.messenger.store import create_chat_record, get_conn, init_db
|
|
|
|
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
|
|
|
|
|
def register(payload):
|
|
request = Request(
|
|
BASE_URL.rstrip("/") + "/api/v1/users",
|
|
data=json.dumps(payload).encode("utf-8"),
|
|
headers={"Content-Type": "application/json"},
|
|
method="POST",
|
|
)
|
|
try:
|
|
with urlopen(request, timeout=10) as response:
|
|
return response.status
|
|
except HTTPError as error:
|
|
return error.code
|
|
|
|
|
|
def main():
|
|
username = "race_" + uuid.uuid4().hex[:16]
|
|
body = {
|
|
"username": username,
|
|
"display_name": "Concurrent registration",
|
|
"password": "Concurrent-test-pass-92",
|
|
}
|
|
with ThreadPoolExecutor(max_workers=2) as executor:
|
|
statuses = sorted(executor.map(register, (body, body)))
|
|
if statuses != [201, 409]:
|
|
raise SystemExit("Expected one 201 and one 409 for concurrent duplicate registration")
|
|
|
|
conn = get_conn()
|
|
try:
|
|
before = conn.execute("SELECT count(*) AS count FROM chats").fetchone()["count"]
|
|
migration_count = conn.execute(
|
|
"SELECT count(*) AS count FROM schema_migrations"
|
|
).fetchone()["count"]
|
|
finally:
|
|
conn.close()
|
|
if migration_count != 1:
|
|
raise SystemExit("Unexpected migration count before idempotence check")
|
|
|
|
try:
|
|
create_chat_record(str(uuid.uuid4()), "rollback check", [str(uuid.uuid4())])
|
|
except ForeignKeyViolation:
|
|
pass
|
|
else:
|
|
raise SystemExit("Expected unknown chat member to violate the foreign key")
|
|
|
|
conn = get_conn()
|
|
try:
|
|
after = conn.execute("SELECT count(*) AS count FROM chats").fetchone()["count"]
|
|
finally:
|
|
conn.close()
|
|
if after != before:
|
|
raise SystemExit("Chat and membership transaction was not rolled back")
|
|
|
|
init_db()
|
|
conn = get_conn()
|
|
try:
|
|
migration_count_after = conn.execute(
|
|
"SELECT count(*) AS count FROM schema_migrations"
|
|
).fetchone()["count"]
|
|
finally:
|
|
conn.close()
|
|
if migration_count_after != migration_count:
|
|
raise SystemExit("Rerunning migrations changed the migration ledger")
|
|
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"duplicate_registration_statuses": statuses,
|
|
"chat_rollback": "PASS",
|
|
"migration_rerun": "PASS",
|
|
"database_driver": "PostgreSQL",
|
|
},
|
|
indent=2,
|
|
)
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|