Document task DB access and unify background task DB handling

This commit is contained in:
2026-04-17 17:18:49 +02:00
parent 16687b0520
commit 5e5d7c34b2
12 changed files with 139 additions and 90 deletions

View File

@@ -0,0 +1,44 @@
"""Tests for the shared background task database helper."""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
import pytest
from app.tasks.db import task_db
class FakeSettings:
database_path = "/tmp/fake.db"
@pytest.mark.asyncio
async def test_task_db_opens_and_closes_connection() -> None:
"""``task_db`` must open a DB connection and close it after use."""
fake_db = AsyncMock()
fake_db.close = AsyncMock()
with patch("app.tasks.db.open_db", new_callable=AsyncMock, return_value=fake_db) as mock_open_db:
async with task_db(FakeSettings()) as db:
assert db is fake_db
mock_open_db.assert_awaited_once_with("/tmp/fake.db")
fake_db.close.assert_awaited_once()
@pytest.mark.asyncio
async def test_task_db_closes_connection_on_exception() -> None:
"""``task_db`` must close the connection even when the body raises."""
fake_db = AsyncMock()
fake_db.close = AsyncMock()
with patch(
"app.tasks.db.open_db",
new_callable=AsyncMock,
return_value=fake_db,
), pytest.raises(RuntimeError, match="boom"):
async with task_db(FakeSettings()):
raise RuntimeError("boom")
fake_db.close.assert_awaited_once()