forked from mtusi2026/mtusi2026lab7
лр7: Docker-прогон, evidence, исправления
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import call, check, compose_output, new_user, psql, run_tests
|
||||
|
||||
|
||||
def sql_value(sql):
|
||||
code, output, error = psql(sql)
|
||||
check(code == 0, f"psql failed: {error}")
|
||||
return output
|
||||
|
||||
|
||||
def test_create_chat_rolls_back():
|
||||
alice = new_user("rollback")
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
inserted_before = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
|
||||
|
||||
call("POST", "/api/v1/chats", 400, token=alice["token"],
|
||||
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
|
||||
|
||||
left = sql_value(f"SELECT count(*) FROM chats WHERE title = '{title}'")
|
||||
orphans = sql_value("SELECT count(*) FROM chats c WHERE NOT EXISTS "
|
||||
"(SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)")
|
||||
inserted_after = inserted_before
|
||||
deadline = time.monotonic() + 15
|
||||
while inserted_after == inserted_before and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
inserted_after = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
|
||||
print(f"chat with unknown member -> 400; rows with this title: {left}; chats without members: {orphans}; "
|
||||
f"chats insert counter: {inserted_before} -> {inserted_after}")
|
||||
check(left == "0" and orphans == "0", "chat row survived the failed transaction")
|
||||
check(inserted_after > inserted_before, "the chat row was never inserted, rollback is not shown")
|
||||
print("PASS: chat row was inserted and then rolled back together with members")
|
||||
|
||||
|
||||
def test_message_needs_membership_in_db():
|
||||
code, _, error = psql("INSERT INTO messages (id, chat_id, sender_id, text) "
|
||||
f"VALUES ('{uuid.uuid4()}', '{uuid.uuid4()}', '{uuid.uuid4()}', convert_to('direct insert', 'UTF8'))")
|
||||
print(f"direct INSERT of a message from a non-member -> exit code {code}: {error.splitlines()[0] if error else ''}")
|
||||
check(code != 0 and "foreign key" in error, "database accepted a message from a non-member")
|
||||
print("PASS: the database itself rejects a message from a non-member")
|
||||
|
||||
|
||||
def test_password_is_argon2id():
|
||||
user = new_user("hash")
|
||||
stored = sql_value(f"SELECT password_hash FROM users WHERE username = '{user['username']}'")
|
||||
print(f"stored password: {stored[:31]}... (length {len(stored)})")
|
||||
check(stored.startswith("$argon2id$") and user["password"] not in stored, "password is not an Argon2id hash")
|
||||
print("PASS: password is stored as Argon2id hash")
|
||||
|
||||
|
||||
def test_unique_username_constraint():
|
||||
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
|
||||
"WHERE conrelid = 'users'::regclass AND contype = 'u'")
|
||||
print(f"unique constraint on users: {constraint}")
|
||||
check(constraint == "UNIQUE (username)", "no unique constraint on username")
|
||||
print("PASS: username is unique in the database")
|
||||
|
||||
|
||||
def test_migrations_are_not_repeated():
|
||||
versions = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
|
||||
print(f"applied migrations: {versions}; running the migrate service once more")
|
||||
output = compose_output("run", "--rm", "--no-deps", "-T", "migrate")
|
||||
again = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
|
||||
last_log = [line for line in output.splitlines() if "Migrations applied" in line][-1]
|
||||
print(f"after the second run: {again}; log: {last_log.split('messenger.db: ')[-1]}")
|
||||
check(again == versions and "none" in last_log, "migrations were applied again")
|
||||
print("PASS: migrations are applied once, a repeated run does nothing")
|
||||
|
||||
|
||||
def test_replicas_do_not_migrate():
|
||||
"""lab3: миграции применяет только сервис migrate, API-реплики лишь проверяют схему."""
|
||||
logs = compose_output("logs", "api").splitlines()
|
||||
checked = [line for line in logs if "Schema is up to date" in line]
|
||||
migrated = [line for line in logs if "Migrations applied" in line]
|
||||
migrate_exit = compose_output("ps", "-a", "--format", "{{.Status}}", "migrate").strip()
|
||||
print(f"api replicas that checked the schema at start: {len(checked)}; api log lines 'Migrations applied': "
|
||||
f"{len(migrated)}; migrate service: {migrate_exit}")
|
||||
check(checked and not migrated, "api replicas must not apply migrations")
|
||||
check(migrate_exit.startswith("Exited (0)"), "migrate service must finish with exit code 0")
|
||||
print("PASS: only the migrate service applies migrations, replicas wait for the schema")
|
||||
|
||||
|
||||
def test_idempotency_key_is_unique_in_db():
|
||||
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
|
||||
"WHERE conname = 'messages_idempotency_key'")
|
||||
print(f"unique constraint for Idempotency-Key: {constraint}")
|
||||
check(constraint == "UNIQUE (chat_id, sender_id, idempotency_key)", "no unique constraint for idempotency keys")
|
||||
print("PASS: one message per (chat, sender, Idempotency-Key) is enforced by the database")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([
|
||||
test_create_chat_rolls_back,
|
||||
test_message_needs_membership_in_db,
|
||||
test_password_is_argon2id,
|
||||
test_unique_username_constraint,
|
||||
test_migrations_are_not_repeated,
|
||||
test_replicas_do_not_migrate,
|
||||
test_idempotency_key_is_unique_in_db,
|
||||
])
|
||||
Reference in New Issue
Block a user