ЛР2: PostgreSQL, сессии (Basic + Bearer), Compose, миграции
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Отдельная тестовая база; задаётся до импорта приложения (настройки читаются при импорте).
|
||||
TEST_DB_NAME = "messenger_test"
|
||||
os.environ["APP_CONFIG__DB__NAME"] = TEST_DB_NAME
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from core.db import build_url, engine
|
||||
from main import app
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parents[1] / "app"
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def test_database():
|
||||
# CREATE DATABASE нельзя выполнить в транзакции, поэтому AUTOCOMMIT.
|
||||
admin = create_engine(build_url().set(database="postgres"), isolation_level="AUTOCOMMIT")
|
||||
with admin.connect() as connection:
|
||||
exists = connection.scalar(text("SELECT 1 FROM pg_database WHERE datname = :name"), {"name": TEST_DB_NAME})
|
||||
if not exists:
|
||||
connection.execute(text(f'CREATE DATABASE "{TEST_DB_NAME}"'))
|
||||
admin.dispose()
|
||||
|
||||
command.upgrade(Config(str(APP_DIR / "alembic.ini")), "head")
|
||||
yield
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_database():
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("TRUNCATE users, sessions, chats, chat_members, messages"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return {"Authorization": "Basic " + credential}
|
||||
|
||||
|
||||
def login(client, username, password=PASSWORD):
|
||||
response = client.post("/api/v1/auth/sessions", headers=basic(username, password))
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": "Bearer " + token}
|
||||
|
||||
|
||||
def create_user(client, username):
|
||||
"""Регистрация + вход; заголовок авторизации — в поле "auth"."""
|
||||
response = client.post("/api/v1/users", json={"username": username, "display_name": "Имя " + username,
|
||||
"password": PASSWORD})
|
||||
assert response.status_code == 201
|
||||
user = response.json()
|
||||
user["token"] = login(client, username)["token"]
|
||||
user["auth"] = bearer(user["token"])
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def alice(client):
|
||||
return create_user(client, "alice")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bob(client):
|
||||
return create_user(client, "bob")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def eve(client):
|
||||
return create_user(client, "eve")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def chat(client, alice, bob):
|
||||
"""Чат alice и bob; eve в него не входит."""
|
||||
response = client.post("/api/v1/chats", headers=alice["auth"],
|
||||
json={"title": "Тестовый чат", "member_ids": [alice["id"], bob["id"]]})
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
|
||||
def assert_error(response, status_code, code):
|
||||
assert response.status_code == status_code
|
||||
body = response.json()
|
||||
assert body["error"]["code"] == code
|
||||
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
Reference in New Issue
Block a user