94 lines
2.5 KiB
Python
94 lines
2.5 KiB
Python
"""Тесты TTL-кеша шаблонов из БД (Блок 4.5): кеш, фолбэк и ошибки БД."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from common.texts import TEMPLATES
|
|
from common.texts.store import TemplateStore
|
|
|
|
|
|
async def test_uses_db_values() -> None:
|
|
async def loader() -> dict[str, str]:
|
|
return {"info.help": "текст из БД"}
|
|
|
|
store = TemplateStore(loader=loader, ttl=60)
|
|
|
|
assert await store.get("info.help") == "текст из БД"
|
|
|
|
|
|
async def test_falls_back_to_code_for_missing_key() -> None:
|
|
async def loader() -> dict[str, str]:
|
|
return {"info.help": "текст из БД"}
|
|
|
|
store = TemplateStore(loader=loader, ttl=60)
|
|
|
|
assert await store.get("economy.top") == TEMPLATES["economy.top"]
|
|
|
|
|
|
async def test_falls_back_when_db_unavailable() -> None:
|
|
async def loader() -> dict[str, str]:
|
|
raise RuntimeError("БД недоступна")
|
|
|
|
store = TemplateStore(loader=loader, ttl=60)
|
|
|
|
assert await store.get("info.help") == TEMPLATES["info.help"]
|
|
|
|
|
|
async def test_caches_within_ttl() -> None:
|
|
calls = 0
|
|
|
|
async def loader() -> dict[str, str]:
|
|
nonlocal calls
|
|
calls += 1
|
|
return {"info.help": f"v{calls}"}
|
|
|
|
store = TemplateStore(loader=loader, ttl=60)
|
|
|
|
assert await store.get("info.help") == "v1"
|
|
assert await store.get("info.help") == "v1"
|
|
assert calls == 1
|
|
|
|
|
|
async def test_reloads_when_cache_expired() -> None:
|
|
calls = 0
|
|
|
|
async def loader() -> dict[str, str]:
|
|
nonlocal calls
|
|
calls += 1
|
|
return {"info.help": f"v{calls}"}
|
|
|
|
store = TemplateStore(loader=loader, ttl=0)
|
|
|
|
assert await store.get("info.help") == "v1"
|
|
assert await store.get("info.help") == "v2"
|
|
|
|
|
|
async def test_clear_forces_reload() -> None:
|
|
calls = 0
|
|
|
|
async def loader() -> dict[str, str]:
|
|
nonlocal calls
|
|
calls += 1
|
|
return {"info.help": f"v{calls}"}
|
|
|
|
store = TemplateStore(loader=loader, ttl=600)
|
|
assert await store.get("info.help") == "v1"
|
|
|
|
store.clear()
|
|
|
|
assert await store.get("info.help") == "v2"
|
|
|
|
|
|
async def test_failed_load_is_not_retried_on_every_call() -> None:
|
|
calls = 0
|
|
|
|
async def loader() -> dict[str, str]:
|
|
nonlocal calls
|
|
calls += 1
|
|
raise RuntimeError("БД недоступна")
|
|
|
|
store = TemplateStore(loader=loader, ttl=60)
|
|
|
|
assert await store.get("info.help") == TEMPLATES["info.help"]
|
|
assert await store.get("info.help") == TEMPLATES["info.help"]
|
|
assert calls == 1
|