forked from mtusi2026/mtusi2026lab5
72 lines
2.4 KiB
Python
72 lines
2.4 KiB
Python
"""Восстановление после обрыва AMQP при объявлении топологии"""
|
|
|
|
import asyncio
|
|
from datetime import UTC, datetime
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
from aiormq import spec
|
|
|
|
import infrastructure.broker.rabbit as rabbit_module
|
|
from domain.jobs import JobMessageSchema
|
|
from infrastructure.broker import RabbitBrokerManager
|
|
|
|
|
|
def connection(fail_bind: bool):
|
|
bound = False
|
|
|
|
async def bind(*args, **kwargs):
|
|
nonlocal bound
|
|
if fail_bind:
|
|
raise ConnectionError("connection lost during queue.bind")
|
|
bound = True
|
|
|
|
async def publish(*args, **kwargs):
|
|
if not bound:
|
|
raise ConnectionError("mandatory message was unroutable")
|
|
return spec.Basic.Ack()
|
|
|
|
exchange = SimpleNamespace(publish=AsyncMock(side_effect=publish))
|
|
queue = SimpleNamespace(bind=AsyncMock(side_effect=bind))
|
|
channel = SimpleNamespace(
|
|
set_qos=AsyncMock(),
|
|
declare_exchange=AsyncMock(return_value=exchange),
|
|
declare_queue=AsyncMock(return_value=queue),
|
|
)
|
|
return SimpleNamespace(
|
|
channel=AsyncMock(return_value=channel), ready=AsyncMock(), close=AsyncMock()
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("reopen", [False, True])
|
|
def test_publish_recovers_after_connection_loss_during_binding(
|
|
tmp_path, monkeypatch, reopen
|
|
):
|
|
url_file = tmp_path / "broker_url"
|
|
url_file.write_text("amqp://synthetic")
|
|
first, second = connection(True), connection(False)
|
|
connections = ([connection(False)] if reopen else []) + [first, second]
|
|
connect = AsyncMock(side_effect=connections)
|
|
monkeypatch.setattr(rabbit_module.aio_pika, "connect_robust", connect)
|
|
message = JobMessageSchema(
|
|
job_id=uuid4(), attachment_id=uuid4(), attempt=1, created_at=datetime.now(UTC)
|
|
)
|
|
|
|
async def run():
|
|
broker = RabbitBrokerManager(url_file, 2)
|
|
try:
|
|
if reopen:
|
|
await broker.publish(message)
|
|
await broker.close()
|
|
with pytest.raises(ConnectionError, match="queue.bind"):
|
|
await broker.publish(message)
|
|
await broker.publish(message)
|
|
assert connect.await_count == (3 if reopen else 2)
|
|
first.close.assert_awaited_once()
|
|
finally:
|
|
await broker.close()
|
|
|
|
asyncio.run(run())
|