init commit: create skeleton from lab1
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
"""Фикстуры для тестов с РЕАЛЬНОЙ PostgreSQL (SQLite не подходит — см. README лабы).
|
||||
|
||||
Перед запуском поднимите БД и создайте тестовую базу:
|
||||
make db-up # docker compose up -d postgres + createdb messenger_test
|
||||
Переменные:
|
||||
TEST_DATABASE_URL по умолчанию postgresql+psycopg://messenger:messenger@localhost:5432/messenger_test
|
||||
TEST_USE_MIGRATIONS=1 строить схему через `alembic upgrade head` вместо Base.metadata.create_all
|
||||
"""
|
||||
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.main import create_app
|
||||
from app.models import Base
|
||||
|
||||
DEFAULT_TEST_DATABASE_URL = (
|
||||
"postgresql+psycopg://messenger:messenger@localhost:5432/messenger_test"
|
||||
)
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
return os.environ.get("TEST_DATABASE_URL", DEFAULT_TEST_DATABASE_URL)
|
||||
|
||||
|
||||
def _alembic_config(url: str) -> Config:
|
||||
config = Config("alembic.ini")
|
||||
config.set_main_option("sqlalchemy.url", url.replace("%", "%%"))
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def database_url() -> str:
|
||||
return _database_url()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def db_engine(database_url: str) -> Iterator[Engine]:
|
||||
engine = create_engine(database_url)
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
except Exception as error: # noqa: BLE001
|
||||
pytest.exit(
|
||||
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
|
||||
f"{type(error).__name__}. Выполните `make db-up`.",
|
||||
returncode=2,
|
||||
)
|
||||
|
||||
# Чистая схема на старте сессии: тесты не зависят от прошлых запусков.
|
||||
Base.metadata.drop_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
|
||||
if os.environ.get("TEST_USE_MIGRATIONS") == "1":
|
||||
command.upgrade(_alembic_config(database_url), "head")
|
||||
else:
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
yield engine
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_db(db_engine: Engine) -> Iterator[None]:
|
||||
"""Пустые таблицы перед каждым тестом (приложение коммитит, откат не годится)."""
|
||||
names = ", ".join(f'"{table.name}"' for table in Base.metadata.sorted_tables)
|
||||
if names:
|
||||
with db_engine.begin() as connection:
|
||||
connection.execute(text(f"TRUNCATE {names} RESTART IDENTITY CASCADE"))
|
||||
yield
|
||||
|
||||
|
||||
def build_settings(database_url: str, **overrides: object) -> Settings:
|
||||
values: dict[str, object] = {
|
||||
"app_host": "127.0.0.1",
|
||||
"app_port": 8080,
|
||||
"app_env": "test",
|
||||
"max_messages": 1000,
|
||||
"max_in_flight": 32,
|
||||
"log_level": "CRITICAL",
|
||||
"database_url": database_url,
|
||||
"session_ttl_seconds": 300,
|
||||
"db_pool_size": 10,
|
||||
"db_max_overflow": 10,
|
||||
}
|
||||
values.update(overrides)
|
||||
return Settings(_env_file=None, **values) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def settings(database_url: str) -> Settings:
|
||||
return build_settings(database_url)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_settings(database_url: str) -> Callable[..., Settings]:
|
||||
"""Settings с переопределениями: make_settings(session_ttl_seconds=1)."""
|
||||
|
||||
def factory(**overrides: object) -> Settings:
|
||||
return build_settings(database_url, **overrides)
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(settings: Settings):
|
||||
application = create_app(settings)
|
||||
|
||||
@application.get("/__test__/explode", include_in_schema=False)
|
||||
def explode() -> None:
|
||||
raise RuntimeError("test-secret")
|
||||
|
||||
return application
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app) -> Iterator[TestClient]:
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client_no_raise(app) -> Iterator[TestClient]:
|
||||
with TestClient(app, raise_server_exceptions=False) as test_client:
|
||||
yield test_client
|
||||
Reference in New Issue
Block a user