Refactor blocklist import registration to async startup flow
This commit is contained in:
@@ -300,10 +300,9 @@ class TestApplySchedule:
|
||||
class TestRegister:
|
||||
"""Tests for :func:`~app.tasks.blocklist_import.register`."""
|
||||
|
||||
def test_register_calls_apply_schedule_via_event_loop(self) -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_calls_apply_schedule(self) -> None:
|
||||
"""``register`` must call ``_apply_schedule`` after reading the stored config."""
|
||||
import asyncio
|
||||
|
||||
from app.tasks.blocklist_import import register
|
||||
|
||||
app = MagicMock()
|
||||
@@ -324,52 +323,10 @@ class TestRegister:
|
||||
new_callable=AsyncMock,
|
||||
return_value=config,
|
||||
), patch("app.tasks.blocklist_import._apply_schedule") as mock_apply:
|
||||
# Use a fresh event loop to avoid interference from pytest-asyncio.
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
with patch("asyncio.get_event_loop", return_value=loop):
|
||||
register(app)
|
||||
finally:
|
||||
loop.close()
|
||||
await register(app)
|
||||
|
||||
mock_apply.assert_called_once_with(app, config)
|
||||
|
||||
def test_register_falls_back_to_ensure_future_on_runtime_error(self) -> None:
|
||||
"""When ``run_until_complete`` raises ``RuntimeError``, ``ensure_future`` is used."""
|
||||
from app.tasks.blocklist_import import register
|
||||
|
||||
app = MagicMock()
|
||||
app.state.db = MagicMock()
|
||||
app.state.db.close = AsyncMock()
|
||||
app.state.settings = MagicMock(database_path="/tmp/fake.db")
|
||||
app.state.scheduler = MagicMock()
|
||||
|
||||
config = ScheduleConfig(frequency=ScheduleFrequency.daily)
|
||||
|
||||
mock_loop = MagicMock()
|
||||
mock_loop.run_until_complete.side_effect = RuntimeError("already running")
|
||||
|
||||
def _close_coro(coro: Any) -> None:
|
||||
coro.close()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"app.tasks.blocklist_import.open_db",
|
||||
new_callable=AsyncMock,
|
||||
return_value=app.state.db,
|
||||
),
|
||||
patch(
|
||||
"app.tasks.blocklist_import.blocklist_service.get_schedule",
|
||||
new_callable=AsyncMock,
|
||||
return_value=config,
|
||||
),
|
||||
patch("asyncio.get_event_loop", return_value=mock_loop),
|
||||
patch("asyncio.ensure_future", side_effect=_close_coro) as mock_ensure_future,
|
||||
):
|
||||
register(app)
|
||||
|
||||
mock_ensure_future.assert_called_once()
|
||||
|
||||
|
||||
class TestReschedule:
|
||||
"""Tests for :func:`~app.tasks.blocklist_import.reschedule`."""
|
||||
|
||||
Reference in New Issue
Block a user