Files
mtusi2026lab2/student-tests/db_integrity_test.py

48 lines
2.4 KiB
Python
Executable File

#!/usr/bin/env python3
import concurrent.futures
import uuid
from stack import BASE_URL, Client, check, compose, main_wrapper, ok, psql
def main():
c = Client(BASE_URL)
username = "u_race_" + uuid.uuid4().hex[:10]
body = {"username": username, "display_name": "Гонка", "password": "Race-password-123"}
def register(_):
return c.call("POST", "/api/v1/users", [201, 409], body=body)["status"]
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
statuses = list(pool.map(register, range(20)))
check(statuses.count(201) == 1, "exactly one registration must win, got %s" % statuses)
check(statuses.count(409) == 19, "all others must get 409, got %s" % statuses)
check(psql("SELECT count(*) FROM users WHERE username = '%s'" % username) == "1", "exactly one row expected")
ok("20 concurrent registrations of one username -> 1x201, 19x409, 1 row")
alice = c.user("rb")
title = "rollback-" + uuid.uuid4().hex
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
check(psql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == "0", "failed chat creation left a chat row")
check(psql("SELECT count(*) FROM chats c WHERE NOT EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)") == "0",
"chat without members exists")
ok("chat with unknown member -> 400 and transaction rolled back (no orphan chat)")
stored = psql("SELECT password_hash FROM users WHERE username = '%s'" % username)
check(stored.startswith("$argon2id$") and "Race-password-123" not in stored, "password must be an Argon2id hash")
check(psql("SELECT count(*) FROM information_schema.columns WHERE table_name = 'sessions' AND column_name = 'token'") == "0",
"raw tokens must not be stored")
ok("password stored as $argon2id$..., sessions keep only sha256(token)")
before = psql("SELECT (SELECT count(*) FROM schema_migrations) || ':' || (SELECT count(*) FROM users)")
compose("run", "--rm", "--no-deps", "migrate")
compose("run", "--rm", "--no-deps", "migrate")
after = psql("SELECT (SELECT count(*) FROM schema_migrations) || ':' || (SELECT count(*) FROM users)")
check(before == after, "migrations changed data on re-run: %s -> %s" % (before, after))
ok("migrations run twice more: schema_migrations and data unchanged (%s)" % after)
if __name__ == "__main__":
main_wrapper(main)