Files
life-echo/api/tests/test_recompose_retry_policy.py
Sully 53e0065e3e refactor(api): TOML 配置 SSOT、统一错误契约、Auth/事务加固与可观测性 (#33)
配置 SSOT(TOML + .env)
统一错误契约
Auth 与事务边界
Redis / Celery 可靠性:业务 Redis(DB/0)与 Celery broker/backend(DB/1)显式拆分;连接池、sync client
可观测性(OpenTelemetry + LGTM)
2026-05-22 13:44:50 +08:00

88 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""recompose_chapter锁竞争时 retry可配置"""
from __future__ import annotations
from contextlib import contextmanager
from unittest.mock import MagicMock, patch
import pytest
from celery.exceptions import Retry
from app.features.memoir.constants import memoir
from app.tasks.chapter_compose_tasks import recompose_chapter
class _FakeSyncDb:
"""模拟 `with get_sync_db() as session`。"""
def __init__(self, session: MagicMock) -> None:
self._session = session
def __enter__(self) -> MagicMock:
return self._session
def __exit__(self, *exc: object) -> bool:
return False
def test_recompose_retries_when_lock_busy_and_flag_on(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
memoir, "recompose_retry_on_lock_contention", True, raising=False
)
session = MagicMock()
ch = MagicMock()
ch.markdown_compose_dirty = True
ch.user_id = "user-1"
ch.category = "childhood"
session.get.return_value = ch
with (
patch(
"app.tasks.chapter_compose_tasks.get_sync_db",
return_value=_FakeSyncDb(session),
),
patch(
"app.tasks.chapter_compose_tasks.acquire_chapter_pipeline_lock",
return_value=None,
),
):
with patch.object(
recompose_chapter, "retry", side_effect=Retry("lock_busy")
) as mock_retry:
with pytest.raises(Retry):
recompose_chapter.run("chapter-1")
mock_retry.assert_called_once()
_, kwargs = mock_retry.call_args
assert "countdown" in kwargs
def test_recompose_skips_when_lock_busy_and_flag_off(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
memoir, "recompose_retry_on_lock_contention", False, raising=False
)
session = MagicMock()
ch = MagicMock()
ch.markdown_compose_dirty = True
ch.user_id = "user-1"
ch.category = "childhood"
session.get.return_value = ch
with (
patch(
"app.tasks.chapter_compose_tasks.get_sync_db",
return_value=_FakeSyncDb(session),
),
patch(
"app.tasks.chapter_compose_tasks.acquire_chapter_pipeline_lock",
return_value=None,
),
):
with patch.object(recompose_chapter, "retry") as mock_retry:
out = recompose_chapter.run("chapter-1")
assert out == {"status": "skip_lock_contention"}
mock_retry.assert_not_called()