import asyncio from unittest.mock import AsyncMock from uuid import uuid4 import pytest from app.infra.db.postgresql.workbench_event_hub import WorkbenchEventHub, WorkbenchEventHubManager @pytest.fixture def anyio_backend(): return "asyncio" @pytest.mark.anyio async def test_project_subscribers_share_one_hub_and_idle_close(monkeypatch): start = AsyncMock() close = AsyncMock() monkeypatch.setattr(WorkbenchEventHub, "start", start) monkeypatch.setattr(WorkbenchEventHub, "close", close) manager = WorkbenchEventHubManager(idle_seconds=0.01) project_id = uuid4() async with manager.subscribe(project_id, "postgresql://test/db") as first: async with manager.subscribe(project_id, "postgresql://test/db") as second: assert first is second assert first.subscribers == 2 assert first.subscribers == 1 await asyncio.sleep(0.03) assert len(manager._hubs) == 0 close.assert_awaited_once()