This commit is contained in:
Ivan Sychev committed 2026-11-23 11:04:14 +03:00
1 parent 84ae2122b7
commit 3c4e8e6cee
54 files changed
+4329

No files matched your search

+260
View File
@@ -0,0 +1,260 @@
"""Тесты для точки входа main.py."""
from __future__ import annotations
import asyncio
import logging
import signal
from unittest.mock import AsyncMock, MagicMock
import pytest
import structlog
from src.main import _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
# =========================================================================
# Тесты _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