fix: patch BOT_LOG_FILE at import time for CI/xdist compatibility

This commit is contained in:
ZdenekSrotyr 2026-04-13 13:21:04 +02:00
parent 9a144f8291
commit 1a68decd4e

View file

@ -3,10 +3,22 @@
import asyncio
import os
import sys
import tempfile
from unittest.mock import AsyncMock, patch
import pytest
# Patch BOT_LOG_FILE at import time (before any fixture runs) so that
# bot.py can be imported even when /data/notifications/ doesn't exist.
# This is critical for pytest-xdist where module-scoped fixtures
# may not run before the worker tries to import the module.
_tmp_log = tempfile.mktemp(suffix=".log")
import services.telegram_bot.config as _cfg
_cfg.BOT_LOG_FILE = _tmp_log
# Ensure the bot module is not cached with the old config
sys.modules.pop("services.telegram_bot.bot", None)
def _make_message(text: str, chat_id: int = 10) -> dict:
return {"chat": {"id": chat_id}, "text": text}
@ -17,25 +29,6 @@ def _run(coro):
return asyncio.get_event_loop().run_until_complete(coro)
@pytest.fixture(autouse=True, scope="module")
def patch_bot_log(tmp_path_factory):
"""Patch BOT_LOG_FILE before the bot module is imported so the FileHandler succeeds."""
log_dir = tmp_path_factory.mktemp("notify_bot")
log_file = str(log_dir / "bot.log")
import services.telegram_bot.config as cfg
original = cfg.BOT_LOG_FILE
cfg.BOT_LOG_FILE = log_file
# Remove cached bot module so it re-imports with patched config
sys.modules.pop("services.telegram_bot.bot", None)
yield
cfg.BOT_LOG_FILE = original
sys.modules.pop("services.telegram_bot.bot", None)
class TestHandleMessage:
def test_start_unlinked_user_generates_verification_code(self):
"""'/start' for an unlinked user generates and sends a verification code."""