Files
mtusi2026lab3/student-tests/test_database.py
T
2026-11-02 20:05:33 +03:00

174 lines
5.9 KiB
Python

"""Содержимое PostgreSQL: хеши, ограничения, миграции и атомарность."""
import asyncio
import uuid
import asyncpg
import pytest
from app.db import create_engine
from app.migrate import run_migrations
from conftest import make_settings, run_sql
def test_password_is_stored_as_scrypt_hash_not_plaintext(client, make_user):
one, two = make_user("hash1"), make_user("hash2")
rows = run_sql(
"SELECT username, password_hash FROM users WHERE username = ANY($1)",
[one.username, two.username],
)
hashes = {row["username"]: row["password_hash"] for row in rows}
assert hashes[one.username].startswith("scrypt$")
assert one.password not in hashes[one.username]
assert hashes[one.username] != hashes[two.username]
def test_same_password_gives_different_hashes(client):
password = "same-password-for-both"
for _ in range(2):
client.post(
"/api/v1/users",
json={
"username": "sp_" + uuid.uuid4().hex[:10],
"display_name": "x",
"password": password,
},
)
rows = run_sql("SELECT password_hash FROM users ORDER BY created_at DESC LIMIT 2")
assert rows[0]["password_hash"] != rows[1]["password_hash"]
def test_session_table_keeps_token_hash_not_token(client, alice):
rows = run_sql(
"SELECT token_hash FROM sessions WHERE user_id = $1", uuid.UUID(alice.id)
)
assert len(rows) == 1
assert len(rows[0]["token_hash"]) == 64 and rows[0]["token_hash"] != alice.token
assert alice.token not in rows[0]["token_hash"]
def test_message_is_really_in_the_database(client, alice, chat):
client.post(
"/api/v1/chats/" + chat["id"] + "/messages",
json={"text": "в базе"},
headers=alice.headers,
)
rows = run_sql(
"SELECT text, sender_id FROM messages WHERE chat_id = $1", uuid.UUID(chat["id"])
)
assert [(r["text"], str(r["sender_id"])) for r in rows] == [("в базе", alice.id)]
def test_migrations_can_run_again_without_duplicating_anything(client, alice):
users_before = run_sql("SELECT count(*) AS n FROM users")[0]["n"]
versions_before = [
r["version"]
for r in run_sql("SELECT version FROM schema_migrations ORDER BY version")
]
async def twice():
engine = create_engine(make_settings())
try:
return [await run_migrations(engine), await run_migrations(engine)]
finally:
await engine.dispose()
first, second = asyncio.run(twice())
assert first == [] and second == []
assert run_sql("SELECT count(*) AS n FROM users")[0]["n"] == users_before
assert [
r["version"]
for r in run_sql("SELECT version FROM schema_migrations ORDER BY version")
] == versions_before
assert versions_before == ["0001_init.sql", "0002_message_requests.sql"]
def test_expected_tables_and_indexes_exist(client):
tables = {
r["tablename"]
for r in run_sql("SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
}
assert {
"users",
"chats",
"chat_members",
"messages",
"sessions",
"schema_migrations",
"message_requests",
} <= tables
indexes = {
r["indexname"]
for r in run_sql("SELECT indexname FROM pg_indexes WHERE schemaname = 'public'")
}
assert "messages_chat_created_idx" in indexes
def count_constraints(table: str, kind: str) -> int:
"""Число ограничений заданного типа у таблицы."""
rows = run_sql(
"SELECT count(*) AS n FROM pg_constraint WHERE conrelid = $1::regclass AND contype::text = $2",
table,
kind,
)
return rows[0]["n"]
def test_primary_and_foreign_keys_are_declared(client):
for table in ("users", "chats", "chat_members", "messages", "sessions"):
assert count_constraints(table, "p") == 1, table
assert count_constraints("users", "u") == 1
assert count_constraints("chat_members", "f") == 2
assert count_constraints("messages", "f") == 2
assert count_constraints("sessions", "f") == 1
def test_database_itself_rejects_bad_rows(client, alice, chat):
chat_id, user_id = uuid.UUID(chat["id"]), uuid.UUID(alice.id)
with pytest.raises(asyncpg.ForeignKeyViolationError):
run_sql(
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, 'x')",
uuid.uuid4(),
uuid.uuid4(),
user_id,
)
with pytest.raises(asyncpg.CheckViolationError):
run_sql(
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, '')",
uuid.uuid4(),
chat_id,
user_id,
)
with pytest.raises(asyncpg.UniqueViolationError):
run_sql(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
chat_id,
user_id,
)
with pytest.raises(asyncpg.CheckViolationError):
run_sql(
"INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, 'BadName', 'x', 'h')",
uuid.uuid4(),
)
def test_chat_creation_is_atomic(client, alice):
"""Неизвестный участник: ни чата, ни участников в БД."""
title = "atomic-" + uuid.uuid4().hex
reply = client.post(
"/api/v1/chats",
json={"title": title, "member_ids": [alice.id, str(uuid.uuid4())]},
headers=alice.headers,
)
assert reply.status_code == 400
assert (
run_sql("SELECT count(*) AS n FROM chats WHERE title = $1", title)[0]["n"] == 0
)
def test_successful_chat_has_all_members_in_database(client, alice, bob, chat):
rows = run_sql(
"SELECT user_id FROM chat_members WHERE chat_id = $1", uuid.UUID(chat["id"])
)
assert {str(r["user_id"]) for r in rows} == {alice.id, bob.id}