Files
etl-service/tests/test_main.py
T
Vlad 271befebbc feat(logging): добавь файл ошибок с ротацией
Warning/error/critical дублируются в JSON-файл. Включается через ERROR_LOG_ENABLED, путь и минимальный уровень задаются в .env. Размер файла ограничен, старые файлы ротируются.
2026-11-24 16:08:58 +03:00

330 lines
10 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.
"""Тесты для точки входа main.py."""
from __future__ import annotations
import asyncio
import json
import logging
import signal
from unittest.mock import AsyncMock, MagicMock
import pytest
import structlog
from src.main import _ErrorFileSink, _run_with_shutdown, configure_logging, main, run
# =========================================================================
# Тесты configure_logging
# =========================================================================
def test_configure_logging_calls_structlog_configure(mocker):
configure_mock = mocker.patch("structlog.configure")
configure_logging()
configure_mock.assert_called_once()
def test_configure_logging_default_level(mocker):
configure_mock = mocker.patch("structlog.configure")
configure_logging()
call_kwargs = configure_mock.call_args.kwargs
assert call_kwargs["wrapper_class"] == structlog.make_filtering_bound_logger(
logging.INFO
)
def test_configure_logging_custom_level(mocker):
configure_mock = mocker.patch("structlog.configure")
configure_logging(level=logging.DEBUG)
call_kwargs = configure_mock.call_args.kwargs
assert call_kwargs["wrapper_class"] == structlog.make_filtering_bound_logger(
logging.DEBUG
)
def test_configure_logging_processors(mocker):
configure_mock = mocker.patch("structlog.configure")
configure_logging()
call_kwargs = configure_mock.call_args.kwargs
processors = call_kwargs["processors"]
assert structlog.contextvars.merge_contextvars in processors
assert structlog.processors.add_log_level in processors
assert call_kwargs["cache_logger_on_first_use"] is True
def test_configure_logging_error_file_disabled(mocker):
configure_mock = mocker.patch("structlog.configure")
configure_logging(error_log_enabled=False)
processors = configure_mock.call_args.kwargs["processors"]
assert not any(isinstance(processor, _ErrorFileSink) for processor in processors)
def test_configure_logging_error_file_enabled(mocker, tmp_path):
configure_mock = mocker.patch("structlog.configure")
log_path = tmp_path / "nested" / "errors.log"
configure_logging(error_log_enabled=True, error_log_path=str(log_path))
processors = configure_mock.call_args.kwargs["processors"]
assert any(isinstance(processor, _ErrorFileSink) for processor in processors)
assert log_path.exists()
def test_error_file_sink_writes_only_configured_levels(tmp_path):
log_path = tmp_path / "errors.log"
sink = _ErrorFileSink(str(log_path), logging.WARNING)
sink(None, "info", {"event": "skip", "level": "info"})
sink(None, "warning", {"event": "warn", "level": "warning"})
sink(None, "error", {"event": "boom", "level": "error"})
lines = log_path.read_text(encoding="utf-8").splitlines()
payloads = [json.loads(line) for line in lines]
assert [payload["event"] for payload in payloads] == ["warn", "boom"]
assert payloads[0]["level"] == "warning"
def test_error_file_sink_writes_traceback(tmp_path):
log_path = tmp_path / "errors.log"
sink = _ErrorFileSink(str(log_path), logging.WARNING)
try:
raise RuntimeError("test failure")
except RuntimeError:
sink(None, "error", {"event": "fail", "level": "error", "exc_info": True})
payload = json.loads(log_path.read_text(encoding="utf-8").splitlines()[0])
assert "RuntimeError: test failure" in payload["exception"]
# =========================================================================
# Тесты _run_with_shutdown
# =========================================================================
async def test_run_with_shutdown_normal_completion():
"""Корутина завершается нормально — _run_with_shutdown возвращается."""
stop_event = asyncio.Event()
async def coro() -> None:
pass
await _run_with_shutdown(coro(), stop_event)
async def test_run_with_shutdown_error_propagates():
"""Корутина выбрасывает исключение — оно пробрасывается наружу."""
stop_event = asyncio.Event()
async def coro() -> None:
raise RuntimeError("pipeline failed")
with pytest.raises(RuntimeError, match="pipeline failed"):
await _run_with_shutdown(coro(), stop_event)
async def test_run_with_shutdown_cancels_on_stop_event():
"""stop_event устанавливается — корутина отменяется."""
stop_event = asyncio.Event()
cancelled = asyncio.Event()
async def coro() -> None:
try:
await asyncio.sleep(3600)
except asyncio.CancelledError:
cancelled.set()
raise
task = asyncio.create_task(_run_with_shutdown(coro(), stop_event))
await asyncio.sleep(0.01)
stop_event.set()
await task
assert cancelled.is_set()
async def test_run_with_shutdown_no_error_on_cancelled_pipeline():
"""Отменённый pipeline не пробрасывает CancelledError наружу."""
stop_event = asyncio.Event()
async def coro() -> None:
await asyncio.sleep(3600)
task = asyncio.create_task(_run_with_shutdown(coro(), stop_event))
await asyncio.sleep(0.01)
stop_event.set()
# Не должно выбрасывать исключение
await task
# =========================================================================
# Тесты main
# =========================================================================
def _make_mock_settings() -> MagicMock:
settings = MagicMock()
settings.s3_bucket = "documents"
settings.s3_prefix = "input/"
settings.embedding_provider.value = "openai"
settings.chunking_strategy.value = "paragraph"
settings.qdrant_collection_name = "documents"
return settings
def _patch_loop_signal_handlers(mocker) -> dict:
"""Патчит add/remove_signal_handler, возвращает dict для callback-перехвата."""
loop = asyncio.get_event_loop()
signal_callbacks: dict = {}
def fake_add_signal_handler(sig, callback):
signal_callbacks[sig] = callback
mocker.patch.object(loop, "add_signal_handler", side_effect=fake_add_signal_handler)
mocker.patch.object(loop, "remove_signal_handler")
return signal_callbacks
async def test_main_calls_run_pipeline(mocker):
"""main() вызывает run_pipeline с настройками."""
mock_settings = _make_mock_settings()
mocker.patch("src.main.get_settings", return_value=mock_settings)
run_pipeline_mock = mocker.patch("src.main.run_pipeline", new_callable=AsyncMock)
_patch_loop_signal_handlers(mocker)
await main()
run_pipeline_mock.assert_awaited_once_with(mock_settings)
async def test_main_propagates_pipeline_error(mocker):
"""Если run_pipeline выбрасывает ошибку, main() пробрасывает её."""
mocker.patch("src.main.get_settings", return_value=_make_mock_settings())
mocker.patch(
"src.main.run_pipeline",
new_callable=AsyncMock,
side_effect=RuntimeError("pipeline crashed"),
)
_patch_loop_signal_handlers(mocker)
with pytest.raises(RuntimeError, match="pipeline crashed"):
await main()
async def test_main_graceful_shutdown_on_signal(mocker):
"""При получении сигнала pipeline отменяется и main() завершается."""
mocker.patch("src.main.get_settings", return_value=_make_mock_settings())
cancelled = asyncio.Event()
async def mock_run_pipeline(settings):
try:
await asyncio.sleep(3600)
except asyncio.CancelledError:
cancelled.set()
raise
mocker.patch("src.main.run_pipeline", side_effect=mock_run_pipeline)
signal_callbacks = _patch_loop_signal_handlers(mocker)
task = asyncio.create_task(main())
await asyncio.sleep(0.01)
# Симулируем сигнал SIGINT
signal_callbacks[signal.SIGINT]()
await task
assert cancelled.is_set()
async def test_main_removes_signal_handlers(mocker):
"""main() удаляет signal handlers после завершения."""
mocker.patch("src.main.get_settings", return_value=_make_mock_settings())
mocker.patch("src.main.run_pipeline", new_callable=AsyncMock)
loop = asyncio.get_event_loop()
remove_mock = mocker.patch.object(loop, "remove_signal_handler")
mocker.patch.object(loop, "add_signal_handler")
await main()
# SIGINT и SIGTERM должны быть удалены
removed_signals = {call.args[0] for call in remove_mock.call_args_list}
assert signal.SIGINT in removed_signals
assert signal.SIGTERM in removed_signals
# =========================================================================
# Тесты run (sync entry point)
# =========================================================================
def test_run_calls_configure_and_asyncio_run(mocker):
"""run() вызывает configure_logging и asyncio.run."""
configure_mock = mocker.patch("src.main.configure_logging")
asyncio_run_mock = mocker.patch("src.main.asyncio.run")
mocker.patch("src.main.main")
run()
configure_mock.assert_called_once()
asyncio_run_mock.assert_called_once()
def test_run_handles_keyboard_interrupt(mocker):
"""run() перехватывает KeyboardInterrupt без ошибки."""
mocker.patch("src.main.configure_logging")
mocker.patch("src.main.main")
mocker.patch("src.main.asyncio.run", side_effect=KeyboardInterrupt)
# Не должно выбрасывать исключение
run()
def test_run_exits_on_fatal_error(mocker):
"""run() логирует и выходит с кодом 1 при фатальной ошибке."""
mocker.patch("src.main.configure_logging")
mocker.patch("src.main.main")
mocker.patch("src.main.asyncio.run", side_effect=RuntimeError("fatal"))
with pytest.raises(SystemExit) as exc_info:
run()
assert exc_info.value.code == 1
def test_error_file_sink_rotates(tmp_path):
log_path = tmp_path / "errors.log"
sink = _ErrorFileSink(
str(log_path),
logging.WARNING,
max_bytes=200,
backup_count=1,
)
for _ in range(20):
sink(
None,
"error",
{"event": "e" * 50, "level": "error", "timestamp": "2026-01-01T00:00:00Z"},
)
assert log_path.exists()
assert (tmp_path / "errors.log.1").exists()