forked from mtusi2026/mtusi2026lab4
Forward-port lab3 SQLAlchemy and Alembic foundation
Carry source f591fa64e525679a31c9db7f942d36c789e1a12f forward from 72a1e57. 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:
@@ -7,12 +7,14 @@ from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import make_url
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import actor, keyed, running_app
|
||||
from conftest import actor, keyed, running_app, upgrade
|
||||
from fakes import MemoryObjectStorage, NullLogger, RecordingPublisher
|
||||
from messenger.attachments.application.commands import ReconcileStorage
|
||||
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
|
||||
@@ -23,7 +25,6 @@ from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
PostgresSingleRun,
|
||||
)
|
||||
from messenger.migrate import migrate
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
@@ -45,12 +46,17 @@ def dsn(database: str) -> str:
|
||||
name = f"reconcile_{uuid4().hex[:12]}"
|
||||
|
||||
async def create() -> None:
|
||||
connection = await asyncpg.connect(database)
|
||||
engine = create_async_engine(
|
||||
make_url(database).set(drivername="postgresql+asyncpg"),
|
||||
isolation_level="AUTOCOMMIT",
|
||||
poolclass=NullPool,
|
||||
)
|
||||
try:
|
||||
await connection.execute(f"CREATE DATABASE {name}")
|
||||
async with engine.connect() as connection:
|
||||
await connection.exec_driver_sql(f"CREATE DATABASE {name}")
|
||||
finally:
|
||||
await connection.close()
|
||||
await migrate(target)
|
||||
await engine.dispose()
|
||||
await upgrade(target)
|
||||
|
||||
target = f"{database.rsplit('/', 1)[0]}/{name}"
|
||||
asyncio.run(create())
|
||||
@@ -80,8 +86,12 @@ class Stand:
|
||||
return await reconciler(command)
|
||||
|
||||
async def sql(self, query: str, *args: Any) -> Any:
|
||||
async with self.database.connection() as connection:
|
||||
return await connection.fetch(query, *args)
|
||||
async with self.database.session() as session:
|
||||
connection = await session.connection()
|
||||
result = await connection.exec_driver_sql(query, args)
|
||||
rows = result.mappings().all() if result.returns_rows else []
|
||||
await session.commit()
|
||||
return rows
|
||||
|
||||
async def upload(self) -> dict[str, Any]:
|
||||
alice, _, _, chat = self.users
|
||||
@@ -279,7 +289,7 @@ def test_any_pass_failure_ends_as_reconcile_failed(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
async def broken(*_args: Any) -> Reconciliation:
|
||||
cancelled = asyncpg.exceptions.QueryCanceledError("statement timeout")
|
||||
cancelled = TimeoutError("statement timeout")
|
||||
raise ExceptionGroup("pass", [cancelled])
|
||||
|
||||
monkeypatch.setattr(entrypoint, "reconcile", broken)
|
||||
@@ -295,7 +305,7 @@ def test_any_pass_failure_ends_as_reconcile_failed(
|
||||
assert stopped.value.code == 1
|
||||
assert captured.out == ""
|
||||
assert "reconcile.failed" in captured.err
|
||||
assert "QueryCanceledError" in captured.err
|
||||
assert "TimeoutError" in captured.err
|
||||
assert "Traceback" not in captured.err
|
||||
|
||||
|
||||
@@ -348,3 +358,33 @@ async def test_storage_failure_mid_pass_ends_it_as_unavailable(dsn: str) -> None
|
||||
with pytest.raises(Unavailable) as failed:
|
||||
await s.run(apply=True, deep=True)
|
||||
assert isinstance(failed.value.__cause__, TimeoutError)
|
||||
|
||||
|
||||
async def test_cancelled_pass_releases_its_autocommit_lock(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def hold() -> None:
|
||||
async with PostgresSingleRun(s.database, LOCK_KEY).hold() as held:
|
||||
assert held
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
task = asyncio.create_task(hold())
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
states = await s.sql(
|
||||
"SELECT a.state FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid "
|
||||
"WHERE l.locktype = 'advisory' AND l.objid = $1",
|
||||
LOCK_KEY,
|
||||
)
|
||||
assert [row["state"] for row in states] == ["idle"]
|
||||
finally:
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
locks = await s.sql(
|
||||
"SELECT count(*) AS total FROM pg_locks WHERE locktype = 'advisory' AND objid = $1",
|
||||
LOCK_KEY,
|
||||
)
|
||||
assert locks[0]["total"] == 0
|
||||
|
||||
Reference in New Issue
Block a user