Forward-port lab3 SQLAlchemy and Alembic foundation
Carry sourcef591fa64e5forward from72a1e57. Preserve lab4 attachment transactions, reconciliation locks, quarantine, and existing schema data through verified legacy adoption. Keep report and evidence work in progress untouched.
This commit is contained in:
+54
-13
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
from base64 import b64encode
|
||||
@@ -9,19 +10,23 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import make_url
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from fakes import MemoryStorageProvider
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.identity.config import IdentitySettings
|
||||
from messenger.main import create_app
|
||||
from messenger.messaging.config import MessagingSettings
|
||||
from messenger.migrate import migrate
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.entrypoints.config import TransportSettings
|
||||
from messenger.shared.infrastructure.postgres import unavailable
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
POSTGRES_IMAGE = re.compile(r"image: (postgres:\S+)")
|
||||
@@ -38,18 +43,53 @@ def docker(*args: str) -> str:
|
||||
return done.stdout.strip()
|
||||
|
||||
|
||||
def migration_config(dsn: str) -> Config:
|
||||
config = Config(str(ROOT / "alembic.ini"))
|
||||
config.attributes["database_url"] = dsn
|
||||
return config
|
||||
|
||||
|
||||
async def upgrade(dsn: str, revision: str = "head") -> None:
|
||||
await asyncio.to_thread(command.upgrade, migration_config(dsn), revision)
|
||||
|
||||
|
||||
async def migrated(dsn: str) -> None:
|
||||
deadline = time.monotonic() + STARTUP_SECONDS
|
||||
while True:
|
||||
try:
|
||||
await migrate(dsn)
|
||||
await upgrade(dsn)
|
||||
return
|
||||
except OSError, asyncpg.PostgresError, asyncpg.InterfaceError:
|
||||
if time.monotonic() > deadline:
|
||||
except Exception as error:
|
||||
if not unavailable(error) or time.monotonic() > deadline:
|
||||
raise
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def sql_connection(dsn: str | None = None) -> AsyncIterator[AsyncConnection]:
|
||||
engine = create_async_engine(
|
||||
make_url(dsn or DATABASE["url"]).set(drivername="postgresql+asyncpg"),
|
||||
poolclass=NullPool,
|
||||
hide_parameters=True,
|
||||
)
|
||||
try:
|
||||
async with engine.begin() as connection:
|
||||
yield connection
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
for port in range(24000, 25000):
|
||||
with socket.socket() as probe:
|
||||
try:
|
||||
probe.bind(("127.0.0.1", port))
|
||||
return port
|
||||
except OSError:
|
||||
continue
|
||||
raise RuntimeError("No free test port in 24000–24999")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def database_for_api(request: pytest.FixtureRequest) -> None:
|
||||
if "api" in request.node.path.parts:
|
||||
@@ -78,7 +118,7 @@ def answering(name: str, *probe: str) -> bool:
|
||||
@pytest.fixture(scope="session")
|
||||
def valkey() -> Iterator[dict[str, str]]:
|
||||
name = f"mtusi-lab4-test-valkey-{uuid4().hex[:8]}"
|
||||
container(name, "-p", "127.0.0.1::6379", image(VALKEY_IMAGE))
|
||||
container(name, "-p", f"127.0.0.1:{free_port()}:6379", image(VALKEY_IMAGE))
|
||||
try:
|
||||
deadline = time.monotonic() + STARTUP_SECONDS
|
||||
while not answering(name, "valkey-cli", "ping"):
|
||||
@@ -94,7 +134,9 @@ def database() -> Iterator[str]:
|
||||
name = f"mtusi-lab4-test-{uuid4().hex[:8]}"
|
||||
tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
|
||||
environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"]
|
||||
container(name, *environment, "-p", "127.0.0.1::5432", image(POSTGRES_IMAGE), *tuning)
|
||||
container(
|
||||
name, *environment, "-p", f"127.0.0.1:{free_port()}:5432", image(POSTGRES_IMAGE), *tuning
|
||||
)
|
||||
try:
|
||||
dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger"
|
||||
asyncio.run(migrated(dsn))
|
||||
@@ -152,12 +194,11 @@ async def client() -> AsyncIterator[AsyncClient]:
|
||||
yield http
|
||||
|
||||
|
||||
async def scalar(sql: str, *args: Any) -> Any:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
return await connection.fetchval(sql, *args)
|
||||
finally:
|
||||
await connection.close()
|
||||
async def scalar(statement: Any, *args: Any) -> Any:
|
||||
async with sql_connection() as connection:
|
||||
if isinstance(statement, str):
|
||||
return (await connection.exec_driver_sql(statement, args)).scalar()
|
||||
return await connection.scalar(statement)
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
|
||||
Reference in New Issue
Block a user