forked from mtusi2026/mtusi2026lab7
Close handshakes and logins that started before a revocation or a password change, converge after a failure in any phase, survive a closed terminal, lock parallel commands and make the drill detect a dead load. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
89 lines
3.2 KiB
Python
89 lines
3.2 KiB
Python
"""Какие ошибки драйвера — недоступность PostgreSQL (change
|
|
`rotation-revocation`, design, решение 10; спек `data-storage`, «Пароль роли
|
|
отвергнут»): `src/infra/db/errors.py`.
|
|
|
|
Отказ входа роли (28P01) — недоступность зависимости (503), а отказ прав
|
|
(42501) и нарушение ограничения (23505) — дефект запроса (500).
|
|
"""
|
|
|
|
from typing import Any
|
|
|
|
import asyncpg
|
|
import pytest
|
|
from sqlalchemy import exc as sa_exc
|
|
|
|
from src.api import dependencies
|
|
from src.infra.db import readiness
|
|
from src.infra.db.errors import is_db_unavailable
|
|
|
|
|
|
def _dbapi_error(sqlstate: str) -> sa_exc.DBAPIError:
|
|
"""Ошибка, как её отдаёт SQLAlchemy: `orig` несёт SQLSTATE asyncpg."""
|
|
original = asyncpg.PostgresError.new({"C": sqlstate, "M": "text"})
|
|
return sa_exc.DBAPIError("SELECT 1", {}, original)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"sqlstate",
|
|
["08006", "53300", "57014", "57P01", "28P01"],
|
|
)
|
|
def test_unavailable(sqlstate: str) -> None:
|
|
assert is_db_unavailable(_dbapi_error(sqlstate))
|
|
|
|
|
|
@pytest.mark.parametrize("sqlstate", ["42501", "23505", "42601", "28000"])
|
|
def test_not_unavailable(sqlstate: str) -> None:
|
|
assert not is_db_unavailable(_dbapi_error(sqlstate))
|
|
|
|
|
|
class _Records:
|
|
"""Логгер модуля: записи (уровень, событие, поля)."""
|
|
|
|
def __init__(self) -> None:
|
|
self.got: list[tuple[str, str, dict[str, Any]]] = []
|
|
|
|
def warning(self, event: str, **fields: Any) -> None:
|
|
self.got.append(("warning", event, fields))
|
|
|
|
def info(self, event: str, **fields: Any) -> None:
|
|
self.got.append(("info", event, fields))
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_readiness_names_refused_login(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Неготовность из-за входа роли — одна запись с SQLSTATE на отказ и одна
|
|
на возврат; прочие отказы готовности записей не дают (их пишет бизнес-
|
|
путь)."""
|
|
records = _Records()
|
|
monkeypatch.setattr(readiness, "logger", records)
|
|
monkeypatch.setattr(
|
|
dependencies,
|
|
"login_readiness",
|
|
readiness.LoginReadiness(),
|
|
)
|
|
outcome: list[Exception | None] = []
|
|
|
|
async def ping(*_args: Any, **_kwargs: Any) -> None:
|
|
error = outcome.pop(0)
|
|
if error is not None:
|
|
raise error
|
|
|
|
monkeypatch.setattr(dependencies, "ping", ping)
|
|
refused = ("warning", "Database refused login", {"sqlstate": "28P01"})
|
|
back = ("info", "Database accepts login again", {})
|
|
for error, ready, want in (
|
|
(TimeoutError(), False, []),
|
|
(_dbapi_error("57P03"), False, []),
|
|
(_dbapi_error("28P01"), False, [refused]),
|
|
(_dbapi_error("28P01"), False, [refused]),
|
|
(TimeoutError(), False, [refused]),
|
|
(None, True, [refused, back]),
|
|
(None, True, [refused, back]),
|
|
(_dbapi_error("28P01"), False, [refused, back, refused]),
|
|
):
|
|
outcome.append(error)
|
|
assert await dependencies.database_ready() is ready
|
|
assert records.got == want
|