fastfood_two/tests/utils.py

51 lines
1.7 KiB
Python

import contextlib
import os
from functools import lru_cache
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from fastfood_two.application.config import Config
from fastfood_two.infrastructure.pg_storage.config import PostgresConfig
from fastfood_two.infrastructure.pg_storage.models import Base
async def db_creator(name: str) -> None:
sql = f"create database {name} with owner test_user;"
async with create_async_engine(
url="postgresql+asyncpg://pi3c:test_password@localhost:5432/test_db",
isolation_level="AUTOCOMMIT",
).begin() as conn:
with contextlib.suppress(ProgrammingError):
await conn.execute(text(sql))
async with create_async_engine(
url=f"postgresql+asyncpg://test_user:test_password@localhost:5432/{name}",
).begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
async def db_deleter(name: str) -> None:
sql = f"DROP DATABASE {name} WITH (FORCE);"
async with create_async_engine(
url="postgresql+asyncpg://pi3c:test_password@localhost:5432/test_db",
isolation_level="AUTOCOMMIT",
).begin() as conn:
await conn.execute(text(sql))
@lru_cache()
def get_test_settings(db_name: str) -> Config:
"""Возвращает настройки приложения"""
return Config(
db=PostgresConfig(
user=os.getenv("DB_USER", "test_user"),
password=os.getenv("DB_PASS", "test_password"),
host=os.getenv("DB_HOST", "localhost"),
port=int(os.getenv("DB_PORT", 5432)),
dbname=db_name,
),
)