forked from mtusi2026/mtusi2026lab2
Implement lab 2 PostgreSQL persistence and expiring sessions
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import base64
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from psycopg import sql
|
||||
from psycopg.conninfo import make_conninfo
|
||||
|
||||
from messenger.app import create_app
|
||||
from messenger.migrate import migrate
|
||||
from messenger.settings import Settings
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PASSWORD = "Учебный:пароль😀-12345"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def settings():
|
||||
password = (ROOT / "secrets/postgres_password").read_text().strip()
|
||||
admin = make_conninfo(
|
||||
host="127.0.0.1", port=55432, user="messenger", password=password, dbname="messenger"
|
||||
)
|
||||
database = "student_tests_" + uuid4().hex
|
||||
with psycopg.connect(admin, autocommit=True) as conn:
|
||||
conn.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(database)))
|
||||
config = Settings(make_conninfo(admin, dbname=database), "redis://127.0.0.1:56379/1")
|
||||
migrate(config.database_url, ROOT / "migrations")
|
||||
yield config
|
||||
with psycopg.connect(admin, autocommit=True) as conn:
|
||||
conn.execute(sql.SQL("DROP DATABASE {} WITH (FORCE)").format(sql.Identifier(database)))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(settings):
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
conn.execute("TRUNCATE users,chats,chat_members,messages,sessions CASCADE")
|
||||
with TestClient(create_app(settings), raise_server_exceptions=False) as client:
|
||||
client.app.state.cache.client.flushdb()
|
||||
yield client
|
||||
|
||||
|
||||
def basic(username, password=PASSWORD):
|
||||
return {
|
||||
"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode()).decode()
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def actors(client):
|
||||
result = []
|
||||
for name in ("alice", "bob", "eve"):
|
||||
r = client.post(
|
||||
"/api/v1/users", json={"username": name, "display_name": name, "password": PASSWORD}
|
||||
)
|
||||
assert r.status_code == 201
|
||||
session = client.post("/api/v1/auth/sessions", headers=basic(name))
|
||||
assert session.status_code == 201
|
||||
result.append({**r.json(), "token": session.json()["token"]})
|
||||
return result
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def room(client, actors):
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + actors[0]["token"]},
|
||||
json={"title": "Чат 👋", "member_ids": [u["id"] for u in actors[:2]]},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
Reference in New Issue
Block a user