feat: добавлена обработка "достоверных" документов, направляемых посредством отправления агенту "достоверных" документов, добавлен функционал добавления title в chunk content`а, обновлены configmap.yaml и values.yaml
This commit is contained in:
1 parent
2b1f85bfc1
commit
dd0a124e36
35 files changed
+3107
-183
No files matched your search
@@ -0,0 +1,614 @@
|
||||
"""Тесты trusted-документов: извлечение текста и пайплайн."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from botocore.exceptions import ClientError
|
||||
from docx import Document as DocxDocument
|
||||
from qdrant_client.models import PointStruct
|
||||
|
||||
from src.config.settings import Settings
|
||||
from src.embeddings.base import EmbeddingProvider
|
||||
from src.parsers.documents import (
|
||||
CorruptDocument,
|
||||
DocumentConversionError,
|
||||
DocumentFormatMismatch,
|
||||
DocumentTextExtractor,
|
||||
DocumentUnpackLimitExceeded,
|
||||
EmptyDocument,
|
||||
UnsupportedDocumentFormat,
|
||||
)
|
||||
from src.pipeline.etl import DocumentsPipeline, run_pipeline
|
||||
from src.processors.base import Chunk, Chunker
|
||||
from src.qdrant.client import QdrantRepository
|
||||
from src.s3.client import S3Client
|
||||
|
||||
# =========================================================================
|
||||
# Фикстуры документов
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def _make_docx(paragraphs: list[str], table: list[list[str]] | None = None) -> bytes:
|
||||
"""Генерирует .docx в памяти."""
|
||||
document = DocxDocument()
|
||||
for text in paragraphs:
|
||||
document.add_paragraph(text)
|
||||
if table:
|
||||
doc_table = document.add_table(rows=len(table), cols=len(table[0]))
|
||||
for row_index, row in enumerate(table):
|
||||
for col_index, value in enumerate(row):
|
||||
doc_table.cell(row_index, col_index).text = value
|
||||
|
||||
buffer = io.BytesIO()
|
||||
document.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _make_odt(body: str) -> bytes:
|
||||
"""Генерирует минимальный .odt с заданным телом office:text."""
|
||||
content = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>'
|
||||
'<office:document-content '
|
||||
'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '
|
||||
'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">'
|
||||
"<office:body><office:text>"
|
||||
f"{body}"
|
||||
"</office:text></office:body>"
|
||||
"</office:document-content>"
|
||||
)
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("mimetype", "application/vnd.oasis.opendocument.text")
|
||||
archive.writestr("content.xml", content)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты DocumentTextExtractor
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_extract_docx_paragraphs_and_table():
|
||||
data = _make_docx(["Первый абзац", "Второй абзац"], [["A", "B"]])
|
||||
|
||||
text = DocumentTextExtractor().extract(data, "trusted/report.docx")
|
||||
|
||||
assert "Первый абзац" in text
|
||||
assert "Второй абзац" in text
|
||||
assert "A | B" in text
|
||||
|
||||
|
||||
def test_extract_docx_uppercase_extension():
|
||||
data = _make_docx(["Текст"])
|
||||
|
||||
text = DocumentTextExtractor().extract(data, "trusted/REPORT.DOCX")
|
||||
|
||||
assert text == "Текст"
|
||||
|
||||
|
||||
def test_extract_odt_handles_p_h_s_and_tab():
|
||||
data = _make_odt(
|
||||
"<text:h>Заголовок</text:h>"
|
||||
'<text:p>Первый<text:s text:c="2"/>второй<text:tab/>третий</text:p>'
|
||||
)
|
||||
|
||||
text = DocumentTextExtractor().extract(data, "trusted/report.odt")
|
||||
|
||||
assert "Заголовок" in text
|
||||
assert "Первый второй третий" in text
|
||||
|
||||
|
||||
def test_extract_odt_without_content_xml_is_corrupt():
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("mimetype", "application/vnd.oasis.opendocument.text")
|
||||
|
||||
with pytest.raises(CorruptDocument, match="content.xml"):
|
||||
DocumentTextExtractor().extract(buffer.getvalue(), "report.odt")
|
||||
|
||||
|
||||
def test_unsupported_extension():
|
||||
with pytest.raises(UnsupportedDocumentFormat):
|
||||
DocumentTextExtractor().extract(b"data", "trusted/report.pdf")
|
||||
|
||||
|
||||
def test_extension_without_suffix():
|
||||
with pytest.raises(UnsupportedDocumentFormat):
|
||||
DocumentTextExtractor().extract(b"data", "trusted/report")
|
||||
|
||||
|
||||
def test_docx_magic_mismatch():
|
||||
with pytest.raises(DocumentFormatMismatch):
|
||||
DocumentTextExtractor().extract(b"\xd0\xcf\x11\xe0" + b"data", "report.docx")
|
||||
|
||||
|
||||
def test_doc_magic_mismatch():
|
||||
with pytest.raises(DocumentFormatMismatch):
|
||||
DocumentTextExtractor().extract(b"PK\x03\x04data", "report.doc")
|
||||
|
||||
|
||||
def test_empty_document_is_permanent_error():
|
||||
data = _make_docx([])
|
||||
|
||||
with pytest.raises(EmptyDocument):
|
||||
DocumentTextExtractor().extract(data, "report.docx")
|
||||
|
||||
|
||||
def test_zip_bomb_limit():
|
||||
data = _make_docx(["Текст"])
|
||||
|
||||
with pytest.raises(DocumentUnpackLimitExceeded):
|
||||
DocumentTextExtractor(max_uncompressed_bytes=1).extract(data, "report.docx")
|
||||
|
||||
|
||||
def test_corrupt_docx_is_permanent_error():
|
||||
# ZIP-заголовок есть, но структура docx отсутствует
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("random.txt", "not a docx")
|
||||
|
||||
with pytest.raises(CorruptDocument):
|
||||
DocumentTextExtractor().extract(buffer.getvalue(), "report.docx")
|
||||
|
||||
|
||||
def test_extract_doc_uses_libreoffice(mocker):
|
||||
converted = _make_docx(["Текст из старого doc"])
|
||||
|
||||
def fake_run(command, **kwargs):
|
||||
out_dir = Path(command[command.index("--outdir") + 1])
|
||||
(out_dir / "input.docx").write_bytes(converted)
|
||||
return MagicMock()
|
||||
|
||||
run_mock = mocker.patch("src.parsers.documents.subprocess.run", side_effect=fake_run)
|
||||
|
||||
text = DocumentTextExtractor().extract(
|
||||
b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1old-doc-data",
|
||||
"trusted/legacy.doc",
|
||||
)
|
||||
|
||||
assert text == "Текст из старого doc"
|
||||
command = run_mock.call_args.args[0]
|
||||
assert "--headless" in command
|
||||
assert command[command.index("--convert-to") + 1] == "docx"
|
||||
|
||||
|
||||
def test_extract_doc_without_libreoffice(mocker):
|
||||
mocker.patch(
|
||||
"src.parsers.documents.subprocess.run",
|
||||
side_effect=FileNotFoundError("soffice"),
|
||||
)
|
||||
|
||||
with pytest.raises(DocumentConversionError, match="LibreOffice не найден"):
|
||||
DocumentTextExtractor().extract(
|
||||
b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1old-doc-data",
|
||||
"trusted/legacy.doc",
|
||||
)
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Фикстуры DocumentsPipeline
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def settings() -> Settings:
|
||||
return Settings(
|
||||
s3_bucket="test-bucket",
|
||||
s3_documents_prefix="trusted/",
|
||||
s3_documents_processed_prefix="trusted_processed/",
|
||||
s3_failed_prefix="trusted_failed/",
|
||||
retry_max_attempts=3,
|
||||
retry_base_delay=0.01,
|
||||
retry_max_delay=0.05,
|
||||
document_max_bytes=1024 * 1024,
|
||||
embedding_batch_size=100,
|
||||
embedding_concurrency=1,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_s3_client(settings):
|
||||
client = MagicMock(spec=S3Client)
|
||||
client.start = AsyncMock()
|
||||
client.stop = AsyncMock()
|
||||
client.list_document_files = AsyncMock(return_value=[])
|
||||
client.read_file = AsyncMock()
|
||||
client.move_file = AsyncMock()
|
||||
client.write_error_json = AsyncMock()
|
||||
client.destination_key = MagicMock(
|
||||
side_effect=lambda key, *, source_prefix=None, dest_prefix=None: (
|
||||
f"{dest_prefix}{key[len(source_prefix):]}"
|
||||
)
|
||||
)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_chunker():
|
||||
chunker = MagicMock(spec=Chunker)
|
||||
chunker.chunk = AsyncMock()
|
||||
return chunker
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_embedding_provider():
|
||||
provider = MagicMock(spec=EmbeddingProvider)
|
||||
provider.embed = AsyncMock(return_value=[[0.1, 0.2]])
|
||||
provider.close = AsyncMock()
|
||||
return provider
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_repository():
|
||||
repo = MagicMock(spec=QdrantRepository)
|
||||
repo.start = AsyncMock()
|
||||
repo.stop = AsyncMock()
|
||||
repo.ensure_collection = AsyncMock()
|
||||
repo.delete_by_s3_key = AsyncMock()
|
||||
repo.upsert = AsyncMock()
|
||||
return repo
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_extractor():
|
||||
extractor = MagicMock(spec=DocumentTextExtractor)
|
||||
extractor.extract = MagicMock(return_value="текст документа")
|
||||
return extractor
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pipeline(
|
||||
settings,
|
||||
mock_s3_client,
|
||||
mock_chunker,
|
||||
mock_embedding_provider,
|
||||
mock_repository,
|
||||
mock_extractor,
|
||||
):
|
||||
return DocumentsPipeline(
|
||||
settings=settings,
|
||||
s3_client=mock_s3_client,
|
||||
chunker=mock_chunker,
|
||||
embedding_provider=mock_embedding_provider,
|
||||
repository=mock_repository,
|
||||
extractor=mock_extractor,
|
||||
)
|
||||
|
||||
|
||||
def _single_chunk(text: str, metadata: dict) -> list[Chunk]:
|
||||
return [Chunk(text=text, index=0, metadata=metadata)]
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты DocumentsPipeline
|
||||
# =========================================================================
|
||||
|
||||
|
||||
async def test_process_document_metadata_and_payload(
|
||||
pipeline,
|
||||
mock_s3_client,
|
||||
mock_chunker,
|
||||
mock_embedding_provider,
|
||||
mock_repository,
|
||||
mock_extractor,
|
||||
):
|
||||
"""Документ → текст → чанк → эмбеддинг → удаление старых точек → upsert."""
|
||||
key = "trusted/sub/report.DOCX"
|
||||
mock_s3_client.read_file.return_value = b"file-bytes"
|
||||
mock_chunker.chunk.side_effect = _single_chunk
|
||||
|
||||
await pipeline._process_document(key)
|
||||
|
||||
mock_extractor.extract.assert_called_once_with(b"file-bytes", key)
|
||||
metadata = mock_chunker.chunk.call_args.args[1]
|
||||
assert metadata == {
|
||||
"source_type": "trusted",
|
||||
"s3_key": key,
|
||||
"file_name": "report.DOCX",
|
||||
"format": "docx",
|
||||
"object_index": 0,
|
||||
}
|
||||
mock_embedding_provider.embed.assert_awaited_once_with(["текст документа"])
|
||||
mock_repository.delete_by_s3_key.assert_awaited_once_with(key)
|
||||
mock_repository.upsert.assert_awaited_once()
|
||||
|
||||
points = mock_repository.upsert.call_args.args[0]
|
||||
assert len(points) == 1
|
||||
assert isinstance(points[0], PointStruct)
|
||||
assert points[0].payload["source_type"] == "trusted"
|
||||
assert points[0].payload["s3_key"] == key
|
||||
assert points[0].payload["file_name"] == "report.DOCX"
|
||||
assert points[0].payload["format"] == "docx"
|
||||
assert points[0].payload["text"] == "текст документа"
|
||||
|
||||
# Удаление старых точек выполняется до upsert
|
||||
method_names = [call[0] for call in mock_repository.method_calls]
|
||||
assert method_names.index("delete_by_s3_key") < method_names.index("upsert")
|
||||
|
||||
|
||||
async def test_run_success_moves_to_processed(
|
||||
pipeline, mock_s3_client, mock_chunker
|
||||
):
|
||||
key = "trusted/report.docx"
|
||||
mock_s3_client.list_document_files.return_value = [key]
|
||||
mock_s3_client.read_file.return_value = b"bytes"
|
||||
mock_chunker.chunk.side_effect = _single_chunk
|
||||
|
||||
await pipeline.run()
|
||||
|
||||
mock_s3_client.move_file.assert_awaited_once_with(
|
||||
key,
|
||||
source_prefix="trusted/",
|
||||
dest_prefix="trusted_processed/",
|
||||
)
|
||||
mock_s3_client.write_error_json.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_run_no_documents(
|
||||
pipeline, mock_s3_client, mock_repository
|
||||
):
|
||||
mock_s3_client.list_document_files.return_value = []
|
||||
|
||||
await pipeline.run()
|
||||
|
||||
mock_s3_client.read_file.assert_not_awaited()
|
||||
mock_repository.upsert.assert_not_awaited()
|
||||
mock_s3_client.move_file.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_permanent_error_moved_to_failed_without_retry(
|
||||
pipeline, mock_s3_client, mock_extractor, mocker
|
||||
):
|
||||
sleep_mock = mocker.patch(
|
||||
"src.pipeline.retry.asyncio.sleep", new_callable=AsyncMock
|
||||
)
|
||||
key = "trusted/broken.docx"
|
||||
mock_s3_client.list_document_files.return_value = [key]
|
||||
mock_s3_client.read_file.return_value = b"bytes"
|
||||
mock_extractor.extract.side_effect = DocumentFormatMismatch("bad magic")
|
||||
|
||||
await pipeline.run()
|
||||
|
||||
sleep_mock.assert_not_awaited()
|
||||
mock_s3_client.read_file.assert_awaited_once()
|
||||
mock_s3_client.move_file.assert_awaited_once_with(
|
||||
key,
|
||||
source_prefix="trusted/",
|
||||
dest_prefix="trusted_failed/",
|
||||
)
|
||||
|
||||
error_key, payload = mock_s3_client.write_error_json.call_args.args
|
||||
assert error_key == "trusted_failed/broken.docx"
|
||||
assert payload["error_type"] == "DocumentFormatMismatch"
|
||||
assert payload["message"] == "bad magic"
|
||||
assert payload["key"] == key
|
||||
assert payload["attempts"] == 1
|
||||
assert "time" in payload
|
||||
|
||||
|
||||
async def test_transient_error_retried_then_succeeds(
|
||||
pipeline, mock_s3_client, mock_chunker, mock_repository, mocker
|
||||
):
|
||||
mocker.patch("src.pipeline.retry.asyncio.sleep", new_callable=AsyncMock)
|
||||
key = "trusted/report.docx"
|
||||
error = ClientError(
|
||||
{"Error": {"Code": "InternalError", "Message": "boom"}},
|
||||
"GetObject",
|
||||
)
|
||||
mock_s3_client.list_document_files.return_value = [key]
|
||||
mock_s3_client.read_file.side_effect = [error, b"bytes"]
|
||||
mock_chunker.chunk.side_effect = _single_chunk
|
||||
|
||||
await pipeline.run()
|
||||
|
||||
assert mock_s3_client.read_file.await_count == 2
|
||||
mock_repository.upsert.assert_awaited_once()
|
||||
mock_s3_client.move_file.assert_awaited_once_with(
|
||||
key,
|
||||
source_prefix="trusted/",
|
||||
dest_prefix="trusted_processed/",
|
||||
)
|
||||
mock_s3_client.write_error_json.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_transient_error_exhausted_moves_to_failed(
|
||||
pipeline, mock_s3_client, mocker
|
||||
):
|
||||
mocker.patch("src.pipeline.retry.asyncio.sleep", new_callable=AsyncMock)
|
||||
key = "trusted/report.docx"
|
||||
error = ClientError(
|
||||
{"Error": {"Code": "InternalError", "Message": "boom"}},
|
||||
"GetObject",
|
||||
)
|
||||
mock_s3_client.list_document_files.return_value = [key]
|
||||
mock_s3_client.read_file.side_effect = error
|
||||
|
||||
await pipeline.run()
|
||||
|
||||
assert mock_s3_client.read_file.await_count == 3
|
||||
mock_s3_client.move_file.assert_awaited_once_with(
|
||||
key,
|
||||
source_prefix="trusted/",
|
||||
dest_prefix="trusted_failed/",
|
||||
)
|
||||
_, payload = mock_s3_client.write_error_json.call_args.args
|
||||
assert payload["attempts"] == 3
|
||||
assert payload["error_type"] == "ClientError"
|
||||
|
||||
|
||||
async def test_oversized_document_fails_without_extraction(
|
||||
pipeline, mock_s3_client, mock_extractor
|
||||
):
|
||||
pipeline._settings = Settings(
|
||||
s3_bucket="test-bucket",
|
||||
s3_documents_prefix="trusted/",
|
||||
s3_documents_processed_prefix="trusted_processed/",
|
||||
s3_failed_prefix="trusted_failed/",
|
||||
retry_max_attempts=3,
|
||||
retry_base_delay=0.01,
|
||||
retry_max_delay=0.05,
|
||||
document_max_bytes=10,
|
||||
)
|
||||
key = "trusted/big.docx"
|
||||
mock_s3_client.list_document_files.return_value = [key]
|
||||
mock_s3_client.read_file.return_value = b"x" * 11
|
||||
|
||||
await pipeline.run()
|
||||
|
||||
mock_extractor.extract.assert_not_called()
|
||||
_, payload = mock_s3_client.write_error_json.call_args.args
|
||||
assert payload["error_type"] == "DocumentTooLarge"
|
||||
assert payload["attempts"] == 1
|
||||
|
||||
|
||||
async def test_empty_chunks_is_permanent_error(
|
||||
pipeline, mock_s3_client, mock_chunker
|
||||
):
|
||||
key = "trusted/empty.docx"
|
||||
mock_s3_client.list_document_files.return_value = [key]
|
||||
mock_s3_client.read_file.return_value = b"bytes"
|
||||
mock_chunker.chunk.return_value = []
|
||||
|
||||
await pipeline.run()
|
||||
|
||||
_, payload = mock_s3_client.write_error_json.call_args.args
|
||||
assert payload["error_type"] == "EmptyDocument"
|
||||
assert payload["attempts"] == 1
|
||||
|
||||
|
||||
async def test_process_document_writes_chunks_in_batches(
|
||||
pipeline,
|
||||
mock_s3_client,
|
||||
mock_chunker,
|
||||
mock_embedding_provider,
|
||||
mock_repository,
|
||||
):
|
||||
"""Чанки эмбеддятся и пишутся батчами; старые точки удаляются один раз."""
|
||||
pipeline._settings = pipeline._settings.model_copy(
|
||||
update={"document_chunk_batch_size": 2}
|
||||
)
|
||||
key = "trusted/big.docx"
|
||||
mock_s3_client.read_file.return_value = b"bytes"
|
||||
mock_chunker.chunk.side_effect = lambda text, metadata: [
|
||||
Chunk(text=f"chunk-{index}", index=index, metadata=metadata)
|
||||
for index in range(5)
|
||||
]
|
||||
mock_embedding_provider.embed.side_effect = lambda texts: [
|
||||
[0.1] for _ in texts
|
||||
]
|
||||
|
||||
await pipeline._process_document(key)
|
||||
|
||||
assert mock_embedding_provider.embed.await_count == 3
|
||||
assert mock_repository.delete_by_s3_key.await_count == 1
|
||||
assert mock_repository.upsert.await_count == 3
|
||||
assert [len(call.args[0]) for call in mock_repository.upsert.call_args_list] == [
|
||||
2,
|
||||
2,
|
||||
1,
|
||||
]
|
||||
last_points = mock_repository.upsert.call_args_list[-1].args[0]
|
||||
assert last_points[0].payload["chunk_index"] == 4
|
||||
assert last_points[0].payload["total_chunks"] == 5
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты выбора ветки по PIPELINE_SOURCE
|
||||
# =========================================================================
|
||||
|
||||
|
||||
async def test_run_pipeline_selects_documents(mocker):
|
||||
documents = mocker.patch(
|
||||
"src.pipeline.etl._run_documents_pipeline", new_callable=AsyncMock
|
||||
)
|
||||
csv = mocker.patch("src.pipeline.etl._run_csv_pipeline", new_callable=AsyncMock)
|
||||
settings = Settings(pipeline_source="documents", pipeline_sources="")
|
||||
|
||||
await run_pipeline(settings)
|
||||
|
||||
documents.assert_awaited_once()
|
||||
csv.assert_not_awaited()
|
||||
called_settings = documents.call_args.args[0]
|
||||
assert called_settings.s3_documents_prefix == "trusted/"
|
||||
assert called_settings.qdrant_collection_name == "trusted_documents"
|
||||
|
||||
|
||||
async def test_run_pipeline_defaults_to_csv(mocker):
|
||||
documents = mocker.patch(
|
||||
"src.pipeline.etl._run_documents_pipeline", new_callable=AsyncMock
|
||||
)
|
||||
csv = mocker.patch("src.pipeline.etl._run_csv_pipeline", new_callable=AsyncMock)
|
||||
settings = Settings(pipeline_source="csv", pipeline_sources="")
|
||||
|
||||
await run_pipeline(settings)
|
||||
|
||||
csv.assert_awaited_once()
|
||||
documents.assert_not_awaited()
|
||||
called_settings = csv.call_args.args[0]
|
||||
assert called_settings.s3_prefix == "input/"
|
||||
assert called_settings.qdrant_collection_name == "documents"
|
||||
|
||||
|
||||
async def test_run_pipeline_runs_sources_concurrently(mocker):
|
||||
events = {
|
||||
"csv": asyncio.Event(),
|
||||
"documents": asyncio.Event(),
|
||||
}
|
||||
release = asyncio.Event()
|
||||
|
||||
async def csv_branch(_settings):
|
||||
events["csv"].set()
|
||||
await release.wait()
|
||||
|
||||
async def documents_branch(_settings):
|
||||
events["documents"].set()
|
||||
await release.wait()
|
||||
|
||||
csv = mocker.patch(
|
||||
"src.pipeline.etl._run_csv_pipeline", side_effect=csv_branch
|
||||
)
|
||||
documents = mocker.patch(
|
||||
"src.pipeline.etl._run_documents_pipeline", side_effect=documents_branch
|
||||
)
|
||||
settings = Settings(pipeline_sources="csv,documents")
|
||||
|
||||
task = asyncio.create_task(run_pipeline(settings))
|
||||
await asyncio.wait_for(
|
||||
asyncio.gather(events["csv"].wait(), events["documents"].wait()),
|
||||
timeout=1,
|
||||
)
|
||||
release.set()
|
||||
await task
|
||||
|
||||
csv_settings = csv.call_args.args[0]
|
||||
documents_settings = documents.call_args.args[0]
|
||||
assert csv_settings.qdrant_collection_name == "documents"
|
||||
assert documents_settings.qdrant_collection_name == "trusted_documents"
|
||||
|
||||
|
||||
async def test_run_pipeline_continues_other_sources_on_error(mocker):
|
||||
documents_finished = False
|
||||
|
||||
async def csv_branch(_settings):
|
||||
raise RuntimeError("csv failed")
|
||||
|
||||
async def documents_branch(_settings):
|
||||
nonlocal documents_finished
|
||||
documents_finished = True
|
||||
|
||||
mocker.patch("src.pipeline.etl._run_csv_pipeline", side_effect=csv_branch)
|
||||
mocker.patch(
|
||||
"src.pipeline.etl._run_documents_pipeline", side_effect=documents_branch
|
||||
)
|
||||
settings = Settings(pipeline_sources="csv,documents")
|
||||
|
||||
with pytest.raises(RuntimeError, match="csv failed"):
|
||||
await run_pipeline(settings)
|
||||
|
||||
assert documents_finished
|
||||
@@ -302,12 +302,14 @@ def test_factory_passes_batching_settings():
|
||||
embedding_api_key="key",
|
||||
embedding_batch_size=500,
|
||||
embedding_concurrency=4,
|
||||
embedding_timeout=77,
|
||||
)
|
||||
|
||||
provider = create_embedding_provider(settings)
|
||||
|
||||
assert provider._batch_size == 500
|
||||
assert provider._concurrency == 4
|
||||
assert provider._client.timeout.read == 77
|
||||
|
||||
|
||||
def test_factory_unknown_provider():
|
||||
|
||||
+179
-1
@@ -16,7 +16,7 @@ from src.parsers.base import ParsedObject
|
||||
from src.parsers.csv_content import ContentCsvRowParser
|
||||
from src.parsers.csv_stream import CsvStreamReader
|
||||
from src.pipeline.checkpoint import Checkpoint
|
||||
from src.pipeline.etl import ETLPipeline, create_chunker
|
||||
from src.pipeline.etl import ETLPipeline, _should_prepend_title, create_chunker
|
||||
from src.pipeline.retry import retry_async
|
||||
from src.processors.base import Chunk, Chunker
|
||||
from src.qdrant.client import QdrantRepository
|
||||
@@ -165,6 +165,43 @@ def test_create_chunker_paragraph():
|
||||
assert chunker.__class__.__name__ == "ParagraphChunker"
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты предиката _should_prepend_title
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_should_prepend_title_for_non_excluded_source():
|
||||
excluded = frozenset({"2", "3"})
|
||||
|
||||
assert _should_prepend_title({"type_id": "1"}, excluded) is True
|
||||
|
||||
|
||||
def test_should_prepend_title_skips_excluded_type_ids():
|
||||
excluded = frozenset({"2", "3"})
|
||||
|
||||
assert _should_prepend_title({"type_id": "2"}, excluded) is False
|
||||
assert _should_prepend_title({"type_id": "3"}, excluded) is False
|
||||
|
||||
|
||||
def test_should_prepend_title_missing_type_id():
|
||||
assert _should_prepend_title({}, frozenset({"2", "3"})) is True
|
||||
|
||||
|
||||
def test_should_prepend_title_without_exclusions():
|
||||
assert _should_prepend_title({"type_id": "2"}, frozenset()) is True
|
||||
|
||||
|
||||
def test_should_prepend_title_uses_configured_type_ids():
|
||||
excluded = frozenset({"1"})
|
||||
|
||||
assert _should_prepend_title({"type_id": "1"}, excluded) is False
|
||||
assert _should_prepend_title({"type_id": "2"}, excluded) is True
|
||||
|
||||
|
||||
def test_should_prepend_title_strips_type_id():
|
||||
assert _should_prepend_title({"type_id": " 2 "}, frozenset({"2"})) is False
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Фикстуры для тестов ETLPipeline
|
||||
# =========================================================================
|
||||
@@ -348,6 +385,7 @@ async def test_process_file_single_object(
|
||||
assert isinstance(points[0], PointStruct)
|
||||
assert points[0].vector == [0.1, 0.2, 0.3]
|
||||
assert points[0].payload["text"] == "hello"
|
||||
assert points[0].payload["source_type"] == "csv"
|
||||
assert points[0].payload["source"] == "s3:test-bucket/input/data.csv"
|
||||
assert points[0].payload["s3_bucket"] == "test-bucket"
|
||||
assert points[0].payload["s3_key"] == "input/data.csv"
|
||||
@@ -356,6 +394,146 @@ async def test_process_file_single_object(
|
||||
assert points[0].payload["object_index"] == 0
|
||||
|
||||
|
||||
async def test_process_file_adds_title_to_every_chunk_for_non_telegram_news(
|
||||
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
||||
):
|
||||
"""Для неисключённого источника заголовок добавляется в каждый чанк."""
|
||||
_mock_stream_lines(mock_s3_client, ["title,content,type_id", "Headline,body,1"])
|
||||
mock_csv_reader.iter_objects = _make_async_iter([
|
||||
ParsedObject(text="body", metadata={"title": "Headline", "type_id": "1"}),
|
||||
])
|
||||
|
||||
async def chunk_side_effect(text, metadata):
|
||||
return [
|
||||
Chunk(text="first", index=0, metadata=metadata),
|
||||
Chunk(text="second", index=1, metadata=metadata),
|
||||
]
|
||||
|
||||
mock_chunker.chunk.side_effect = chunk_side_effect
|
||||
mock_embedding_provider.embed.return_value = [[0.1], [0.2]]
|
||||
|
||||
await pipeline._process_file("input/data.csv")
|
||||
|
||||
mock_chunker.chunk.assert_awaited_once()
|
||||
chunk_text, _ = mock_chunker.chunk.await_args.args
|
||||
assert chunk_text == "body"
|
||||
mock_embedding_provider.embed.assert_awaited_once_with(
|
||||
["Headline\n\nfirst", "Headline\n\nsecond"]
|
||||
)
|
||||
|
||||
points = mock_repository.upsert.call_args.kwargs.get("points") or mock_repository.upsert.call_args.args[0]
|
||||
assert [point.payload["title"] for point in points] == ["Headline", "Headline"]
|
||||
assert [point.payload["text"] for point in points] == [
|
||||
"Headline\n\nfirst",
|
||||
"Headline\n\nsecond",
|
||||
]
|
||||
assert [point.payload["chunk_index"] for point in points] == [0, 1]
|
||||
|
||||
|
||||
async def test_process_file_keeps_text_without_title_for_telegram_news(
|
||||
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
||||
):
|
||||
"""Для Telegram-новости заголовок в текст чанка не добавляется."""
|
||||
_mock_stream_lines(mock_s3_client, ["title,content,type_id", "Headline,body,2"])
|
||||
mock_csv_reader.iter_objects = _make_async_iter([
|
||||
ParsedObject(text="body", metadata={"title": "Headline", "type_id": "2"}),
|
||||
])
|
||||
|
||||
async def chunk_side_effect(text, metadata):
|
||||
return [Chunk(text=text, index=0, metadata=metadata)]
|
||||
|
||||
mock_chunker.chunk.side_effect = chunk_side_effect
|
||||
mock_embedding_provider.embed.return_value = [[0.1, 0.2, 0.3]]
|
||||
|
||||
await pipeline._process_file("input/data.csv")
|
||||
|
||||
mock_chunker.chunk.assert_awaited_once()
|
||||
chunk_text, _ = mock_chunker.chunk.await_args.args
|
||||
assert chunk_text == "body"
|
||||
|
||||
points = mock_repository.upsert.call_args.kwargs.get("points") or mock_repository.upsert.call_args.args[0]
|
||||
assert points[0].payload["title"] == "Headline"
|
||||
assert points[0].payload["text"] == "body"
|
||||
|
||||
|
||||
async def test_process_file_keeps_text_without_title_for_vk_news(
|
||||
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
||||
):
|
||||
"""Для VK-новости заголовок в текст чанка не добавляется."""
|
||||
_mock_stream_lines(mock_s3_client, ["title,content,type_id", "Headline,body,3"])
|
||||
mock_csv_reader.iter_objects = _make_async_iter([
|
||||
ParsedObject(text="body", metadata={"title": "Headline", "type_id": "3"}),
|
||||
])
|
||||
|
||||
async def chunk_side_effect(text, metadata):
|
||||
return [Chunk(text=text, index=0, metadata=metadata)]
|
||||
|
||||
mock_chunker.chunk.side_effect = chunk_side_effect
|
||||
mock_embedding_provider.embed.return_value = [[0.1, 0.2, 0.3]]
|
||||
|
||||
await pipeline._process_file("input/data.csv")
|
||||
|
||||
mock_chunker.chunk.assert_awaited_once()
|
||||
chunk_text, _ = mock_chunker.chunk.await_args.args
|
||||
assert chunk_text == "body"
|
||||
|
||||
points = mock_repository.upsert.call_args.kwargs.get("points") or mock_repository.upsert.call_args.args[0]
|
||||
assert points[0].payload["title"] == "Headline"
|
||||
assert points[0].payload["text"] == "body"
|
||||
|
||||
|
||||
async def test_process_file_respects_configured_excluded_type_ids(
|
||||
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
||||
):
|
||||
"""Набор исключённых type_id берётся из настроек."""
|
||||
pipeline._settings = pipeline._settings.model_copy(
|
||||
update={"title_excluded_type_ids": "1"}
|
||||
)
|
||||
_mock_stream_lines(mock_s3_client, ["title,content,type_id", "Headline,body,1"])
|
||||
mock_csv_reader.iter_objects = _make_async_iter([
|
||||
ParsedObject(text="body", metadata={"title": "Headline", "type_id": "1"}),
|
||||
])
|
||||
|
||||
async def chunk_side_effect(text, metadata):
|
||||
return [Chunk(text=text, index=0, metadata=metadata)]
|
||||
|
||||
mock_chunker.chunk.side_effect = chunk_side_effect
|
||||
mock_embedding_provider.embed.return_value = [[0.1, 0.2, 0.3]]
|
||||
|
||||
await pipeline._process_file("input/data.csv")
|
||||
|
||||
chunk_text, _ = mock_chunker.chunk.await_args.args
|
||||
assert chunk_text == "body"
|
||||
mock_embedding_provider.embed.assert_awaited_once_with(["body"])
|
||||
|
||||
points = mock_repository.upsert.call_args.kwargs.get("points") or mock_repository.upsert.call_args.args[0]
|
||||
assert points[0].payload["text"] == "body"
|
||||
|
||||
|
||||
async def test_process_file_skips_empty_title(
|
||||
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
||||
):
|
||||
"""Пустой заголовок не добавляется в текст чанка."""
|
||||
_mock_stream_lines(mock_s3_client, ["title,content,type_id", ",body,1"])
|
||||
mock_csv_reader.iter_objects = _make_async_iter([
|
||||
ParsedObject(text="body", metadata={"title": "", "type_id": "1"}),
|
||||
])
|
||||
|
||||
async def chunk_side_effect(text, metadata):
|
||||
return [Chunk(text=text, index=0, metadata=metadata)]
|
||||
|
||||
mock_chunker.chunk.side_effect = chunk_side_effect
|
||||
mock_embedding_provider.embed.return_value = [[0.1, 0.2, 0.3]]
|
||||
|
||||
await pipeline._process_file("input/data.csv")
|
||||
|
||||
chunk_text, _ = mock_chunker.chunk.await_args.args
|
||||
assert chunk_text == "body"
|
||||
|
||||
points = mock_repository.upsert.call_args.kwargs.get("points") or mock_repository.upsert.call_args.args[0]
|
||||
assert points[0].payload["text"] == "body"
|
||||
|
||||
|
||||
async def test_process_file_multiple_objects(
|
||||
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
||||
):
|
||||
|
||||
@@ -314,3 +314,43 @@ async def test_upsert_honors_retry_after(mock_qdrant, settings, mocker):
|
||||
|
||||
assert mock_instance.upsert.await_count == 2
|
||||
sleep_mock.assert_awaited_once_with(7.0)
|
||||
|
||||
|
||||
# --- Тесты delete_by_s3_key ---
|
||||
|
||||
|
||||
async def test_delete_by_s3_key_filters_payload(mock_qdrant, settings):
|
||||
"""Удаляет точки документа по payload-полю s3_key."""
|
||||
_, mock_instance = mock_qdrant
|
||||
mock_instance.delete = AsyncMock()
|
||||
repo = QdrantRepository(settings)
|
||||
await repo.start()
|
||||
|
||||
await repo.delete_by_s3_key("trusted/report.docx")
|
||||
|
||||
mock_instance.delete.assert_awaited_once()
|
||||
kwargs = mock_instance.delete.call_args.kwargs
|
||||
assert kwargs["collection_name"] == "test-collection"
|
||||
assert kwargs["wait"] is False
|
||||
|
||||
selector = kwargs["points_selector"]
|
||||
condition = selector.filter.must[0]
|
||||
assert condition.key == "s3_key"
|
||||
assert condition.match.value == "trusted/report.docx"
|
||||
|
||||
|
||||
async def test_delete_by_s3_key_retries_transient_error(
|
||||
mock_qdrant, settings, mocker
|
||||
):
|
||||
"""Сетевая ошибка при удалении повторяется."""
|
||||
_, mock_instance = mock_qdrant
|
||||
mock_instance.delete = AsyncMock(
|
||||
side_effect=[ResponseHandlingException(TimeoutError("timeout")), None]
|
||||
)
|
||||
mocker.patch("src.qdrant.client.asyncio.sleep", new_callable=AsyncMock)
|
||||
repo = QdrantRepository(settings)
|
||||
await repo.start()
|
||||
|
||||
await repo.delete_by_s3_key("trusted/report.docx")
|
||||
|
||||
assert mock_instance.delete.await_count == 2
|
||||
@@ -6,6 +6,7 @@ from datetime import UTC, datetime
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from aiohttp import ClientPayloadError
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from src.config.settings import Settings
|
||||
@@ -880,3 +881,183 @@ async def test_stream_file_lines_uses_configured_chunk_size(
|
||||
assert lines == ["a,b", "c,d"]
|
||||
assert mock_body.chunk_size == 4096
|
||||
assert mock_body.closed
|
||||
|
||||
|
||||
# --- Тесты list_document_files ---
|
||||
|
||||
|
||||
async def test_list_document_files_case_insensitive(mock_s3_client_obj, settings):
|
||||
"""Возвращает .doc/.docx/.odt без учёта регистра и только из trusted/."""
|
||||
mock_paginator = MagicMock()
|
||||
prefixes: list[str] = []
|
||||
|
||||
async def async_paginate(*args, **kwargs):
|
||||
prefixes.append(kwargs["Prefix"])
|
||||
yield {
|
||||
"Contents": [
|
||||
{"Key": "trusted/report.DOCX"},
|
||||
{"Key": "trusted/legacy.Doc"},
|
||||
{"Key": "trusted/scan.odt"},
|
||||
{"Key": "trusted/notes.txt"},
|
||||
{"Key": "trusted/archive.csv"},
|
||||
]
|
||||
}
|
||||
|
||||
mock_paginator.paginate = async_paginate
|
||||
mock_s3_client_obj.get_paginator = MagicMock(return_value=mock_paginator)
|
||||
|
||||
client = S3Client(settings)
|
||||
await client.start()
|
||||
|
||||
keys = await client.list_document_files()
|
||||
|
||||
assert keys == ["trusted/legacy.Doc", "trusted/report.DOCX", "trusted/scan.odt"]
|
||||
assert prefixes == ["trusted/"]
|
||||
|
||||
|
||||
async def test_move_file_custom_prefixes(mock_s3_client_obj, settings):
|
||||
"""move_file переносит между заданными префиксами, сохраняя вложенность."""
|
||||
mock_s3_client_obj.copy_object = AsyncMock()
|
||||
mock_s3_client_obj.delete_object = AsyncMock()
|
||||
|
||||
client = S3Client(settings)
|
||||
await client.start()
|
||||
|
||||
await client.move_file(
|
||||
"trusted/sub/report.docx",
|
||||
source_prefix="trusted/",
|
||||
dest_prefix="trusted_processed/",
|
||||
)
|
||||
|
||||
mock_s3_client_obj.copy_object.assert_awaited_once_with(
|
||||
Bucket="test-bucket",
|
||||
Key="trusted_processed/sub/report.docx",
|
||||
CopySource={"Bucket": "test-bucket", "Key": "trusted/sub/report.docx"},
|
||||
MetadataDirective="COPY",
|
||||
)
|
||||
mock_s3_client_obj.delete_object.assert_awaited_once_with(
|
||||
Bucket="test-bucket",
|
||||
Key="trusted/sub/report.docx",
|
||||
)
|
||||
|
||||
|
||||
async def test_write_error_json(mock_s3_client_obj, settings):
|
||||
"""Описание ошибки пишется рядом с файлом как <ключ>.error.json."""
|
||||
mock_s3_client_obj.put_object = AsyncMock()
|
||||
|
||||
client = S3Client(settings)
|
||||
await client.start()
|
||||
|
||||
await client.write_error_json(
|
||||
"trusted_failed/sub/report.docx",
|
||||
{"error_type": "EmptyDocument", "attempts": 1},
|
||||
)
|
||||
|
||||
kwargs = mock_s3_client_obj.put_object.call_args.kwargs
|
||||
assert kwargs["Key"] == "trusted_failed/sub/report.docx.error.json"
|
||||
assert kwargs["ContentType"] == "application/json"
|
||||
assert b'"error_type": "EmptyDocument"' in kwargs["Body"] or (
|
||||
b'"error_type":"EmptyDocument"' in kwargs["Body"]
|
||||
)
|
||||
|
||||
|
||||
class FailingStreamingBody:
|
||||
"""Поток, который обрывается после указанного числа chunks."""
|
||||
|
||||
def __init__(self, chunks: list[bytes], fail_after: int | None = None) -> None:
|
||||
self._chunks = chunks
|
||||
self._fail_after = fail_after
|
||||
self.closed = False
|
||||
|
||||
def iter_chunks(self, chunk_size: int):
|
||||
async def _iter():
|
||||
if self._fail_after is not None and self._fail_after < 0:
|
||||
raise ClientPayloadError("connection lost")
|
||||
for index, chunk in enumerate(self._chunks):
|
||||
yield chunk
|
||||
if self._fail_after is not None and index >= self._fail_after:
|
||||
raise ClientPayloadError("connection lost")
|
||||
|
||||
return _iter()
|
||||
|
||||
async def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
async def test_stream_file_lines_reconnects_after_payload_error(
|
||||
mock_s3_client_obj, settings, mocker
|
||||
):
|
||||
"""Обрыв соединения переподключается с последней целой строки без дублей."""
|
||||
sleep_mock = mocker.patch(
|
||||
"src.s3.client.asyncio.sleep", new_callable=AsyncMock
|
||||
)
|
||||
raw = b"header\nline1\nline2\nline3\n"
|
||||
first_offset = len(b"header\nline1\n")
|
||||
|
||||
def get_object_side_effect(**kwargs):
|
||||
if "Range" in kwargs:
|
||||
start = int(kwargs["Range"].split("=")[1].rstrip("-"))
|
||||
return {"Body": MockStreamingBody([raw[start:]])}
|
||||
return {
|
||||
"Body": FailingStreamingBody(
|
||||
[b"header\nline1\n", b"line2\nline3\n"],
|
||||
fail_after=0,
|
||||
)
|
||||
}
|
||||
|
||||
mock_s3_client_obj.head_object = AsyncMock(
|
||||
return_value={"ContentLength": len(raw)}
|
||||
)
|
||||
mock_s3_client_obj.get_object = AsyncMock(
|
||||
side_effect=get_object_side_effect
|
||||
)
|
||||
|
||||
client = S3Client(settings)
|
||||
await client.start()
|
||||
|
||||
result = [
|
||||
(line, offset)
|
||||
async for line, offset in client.stream_file_lines_with_offsets(
|
||||
"input/data.csv"
|
||||
)
|
||||
]
|
||||
|
||||
assert result == [
|
||||
("header", 7),
|
||||
("line1", first_offset),
|
||||
("line2", first_offset + 6),
|
||||
("line3", first_offset + 12),
|
||||
]
|
||||
assert mock_s3_client_obj.get_object.await_count == 2
|
||||
second_call = mock_s3_client_obj.get_object.await_args_list[1]
|
||||
assert second_call.kwargs["Range"] == f"bytes={first_offset}-"
|
||||
sleep_mock.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_stream_file_lines_fails_after_reconnects_without_progress(
|
||||
mock_s3_client_obj, settings, mocker
|
||||
):
|
||||
"""Если прогресса нет, после лимита переподключений пробрасывается ошибка."""
|
||||
sleep_mock = mocker.patch(
|
||||
"src.s3.client.asyncio.sleep", new_callable=AsyncMock
|
||||
)
|
||||
mock_s3_client_obj.head_object = AsyncMock(return_value={"ContentLength": 100})
|
||||
mock_s3_client_obj.get_object = AsyncMock(
|
||||
return_value={
|
||||
"Body": FailingStreamingBody([], fail_after=-1),
|
||||
}
|
||||
)
|
||||
|
||||
client = S3Client(settings)
|
||||
await client.start()
|
||||
|
||||
with pytest.raises(ClientPayloadError):
|
||||
_ = [
|
||||
(line, offset)
|
||||
async for line, offset in client.stream_file_lines_with_offsets(
|
||||
"input/data.csv"
|
||||
)
|
||||
]
|
||||
|
||||
assert mock_s3_client_obj.get_object.await_count == 3
|
||||
assert sleep_mock.await_count == 2
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Тесты настроек и описания источников пайплайна."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from src.config.settings import PipelineSource, Settings
|
||||
from src.pipeline.sources import (
|
||||
SourceSpec,
|
||||
build_source_specs,
|
||||
settings_for_source,
|
||||
validate_source_specs,
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Тесты Settings.enabled_sources
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_enabled_sources_from_list():
|
||||
settings = Settings(pipeline_sources="csv, documents ,csv")
|
||||
|
||||
assert settings.enabled_sources() == [
|
||||
PipelineSource.CSV,
|
||||
PipelineSource.DOCUMENTS,
|
||||
]
|
||||
|
||||
|
||||
def test_enabled_sources_falls_back_to_single_source():
|
||||
settings = Settings(pipeline_source="documents", pipeline_sources="")
|
||||
|
||||
assert settings.enabled_sources() == [PipelineSource.DOCUMENTS]
|
||||
|
||||
|
||||
def test_enabled_sources_empty_list_falls_back():
|
||||
settings = Settings(pipeline_source="csv", pipeline_sources=" , ")
|
||||
|
||||
assert settings.enabled_sources() == [PipelineSource.CSV]
|
||||
|
||||
|
||||
def test_enabled_sources_rejects_unknown_value():
|
||||
settings = Settings(pipeline_sources="csv,unknown")
|
||||
|
||||
with pytest.raises(ValueError, match="Неизвестный источник"):
|
||||
settings.enabled_sources()
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты Settings.excluded_title_type_ids
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_excluded_title_type_ids_from_list():
|
||||
settings = Settings(title_excluded_type_ids="2, 3 ,4,2, ")
|
||||
|
||||
assert settings.excluded_title_type_ids() == frozenset({"2", "3", "4"})
|
||||
|
||||
|
||||
def test_excluded_title_type_ids_empty_list():
|
||||
settings = Settings(title_excluded_type_ids=" , ")
|
||||
|
||||
assert settings.excluded_title_type_ids() == frozenset()
|
||||
|
||||
|
||||
def test_excluded_title_type_ids_from_env(monkeypatch):
|
||||
monkeypatch.setenv("TITLE_EXCLUDED_TYPE_IDS", "5, 6 ,5")
|
||||
settings = Settings(_env_file=None)
|
||||
|
||||
assert settings.excluded_title_type_ids() == frozenset({"5", "6"})
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты build_source_specs / settings_for_source
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def _settings() -> Settings:
|
||||
return Settings(
|
||||
pipeline_sources="csv,documents",
|
||||
s3_prefix="input/",
|
||||
s3_processed_prefix="processed/",
|
||||
s3_documents_prefix="trusted/",
|
||||
s3_documents_processed_prefix="trusted_processed/",
|
||||
s3_failed_prefix="trusted_failed/",
|
||||
qdrant_collection_name="documents",
|
||||
qdrant_documents_collection_name="trusted_documents",
|
||||
)
|
||||
|
||||
|
||||
def test_build_source_specs_maps_prefixes_and_collections():
|
||||
specs = build_source_specs(_settings())
|
||||
|
||||
assert [spec.name for spec in specs] == [
|
||||
PipelineSource.CSV,
|
||||
PipelineSource.DOCUMENTS,
|
||||
]
|
||||
assert specs[0].input_prefix == "input/"
|
||||
assert specs[0].processed_prefix == "processed/"
|
||||
assert specs[0].failed_prefix is None
|
||||
assert specs[0].collection_name == "documents"
|
||||
|
||||
assert specs[1].input_prefix == "trusted/"
|
||||
assert specs[1].processed_prefix == "trusted_processed/"
|
||||
assert specs[1].failed_prefix == "trusted_failed/"
|
||||
assert specs[1].collection_name == "trusted_documents"
|
||||
|
||||
|
||||
def test_settings_for_csv_source():
|
||||
settings = _settings()
|
||||
spec = build_source_specs(settings)[0]
|
||||
|
||||
source_settings = settings_for_source(settings, spec)
|
||||
|
||||
assert source_settings.pipeline_source == PipelineSource.CSV
|
||||
assert source_settings.s3_prefix == "input/"
|
||||
assert source_settings.s3_processed_prefix == "processed/"
|
||||
assert source_settings.qdrant_collection_name == "documents"
|
||||
|
||||
|
||||
def test_settings_for_documents_source():
|
||||
settings = _settings()
|
||||
spec = build_source_specs(settings)[1]
|
||||
|
||||
source_settings = settings_for_source(settings, spec)
|
||||
|
||||
assert source_settings.pipeline_source == PipelineSource.DOCUMENTS
|
||||
assert source_settings.s3_documents_prefix == "trusted/"
|
||||
assert source_settings.s3_documents_processed_prefix == "trusted_processed/"
|
||||
assert source_settings.s3_failed_prefix == "trusted_failed/"
|
||||
assert source_settings.qdrant_collection_name == "trusted_documents"
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты validate_source_specs
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_validate_accepts_distinct_sources():
|
||||
validate_source_specs(build_source_specs(_settings()))
|
||||
|
||||
|
||||
def test_validate_rejects_empty_sources():
|
||||
with pytest.raises(ValueError, match="ни один источник"):
|
||||
validate_source_specs([])
|
||||
|
||||
|
||||
def test_validate_rejects_duplicate_sources():
|
||||
spec = SourceSpec(
|
||||
name=PipelineSource.CSV,
|
||||
input_prefix="input/",
|
||||
processed_prefix="processed/",
|
||||
failed_prefix=None,
|
||||
collection_name="documents",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="дублироваться"):
|
||||
validate_source_specs([spec, spec])
|
||||
|
||||
|
||||
def test_validate_rejects_overlapping_input_prefixes():
|
||||
csv_spec = SourceSpec(
|
||||
name=PipelineSource.CSV,
|
||||
input_prefix="input/",
|
||||
processed_prefix="processed/",
|
||||
failed_prefix=None,
|
||||
collection_name="documents",
|
||||
)
|
||||
documents_spec = SourceSpec(
|
||||
name=PipelineSource.DOCUMENTS,
|
||||
input_prefix="input/trusted/",
|
||||
processed_prefix="trusted_processed/",
|
||||
failed_prefix="trusted_failed/",
|
||||
collection_name="trusted_documents",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="пересекаются"):
|
||||
validate_source_specs([csv_spec, documents_spec])
|
||||
|
||||
|
||||
def test_validate_rejects_input_equal_to_output():
|
||||
spec = SourceSpec(
|
||||
name=PipelineSource.CSV,
|
||||
input_prefix="input/",
|
||||
processed_prefix="input/",
|
||||
failed_prefix=None,
|
||||
collection_name="documents",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="совпадают или пересекаются"):
|
||||
validate_source_specs([spec])
|
||||
|
||||
|
||||
def test_validate_rejects_failed_overlapping_output():
|
||||
spec = SourceSpec(
|
||||
name=PipelineSource.DOCUMENTS,
|
||||
input_prefix="trusted/",
|
||||
processed_prefix="trusted_processed/",
|
||||
failed_prefix="trusted_processed/failed/",
|
||||
collection_name="trusted_documents",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="failed-префикс"):
|
||||
validate_source_specs([spec])
|
||||
|
||||
|
||||
def test_validate_rejects_same_collection_for_two_sources():
|
||||
csv_spec = SourceSpec(
|
||||
name=PipelineSource.CSV,
|
||||
input_prefix="input/",
|
||||
processed_prefix="processed/",
|
||||
failed_prefix=None,
|
||||
collection_name="shared",
|
||||
)
|
||||
documents_spec = SourceSpec(
|
||||
name=PipelineSource.DOCUMENTS,
|
||||
input_prefix="trusted/",
|
||||
processed_prefix="trusted_processed/",
|
||||
failed_prefix="trusted_failed/",
|
||||
collection_name="shared",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="разные коллекции"):
|
||||
validate_source_specs([csv_spec, documents_spec])
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Полная проверка классификации источников новостей на продовой выгрузке.
|
||||
|
||||
Тест читает ``.data/csv/output.csv`` целиком и сверяет результат предиката
|
||||
``_should_prepend_title`` с независимыми признаками — хостом URL первоисточника.
|
||||
Запускается только по явному запросу, чтобы не замедлять обычный прогон тестов:
|
||||
|
||||
ETL_FULL_DATASET_TEST=1 .venv/bin/python -m pytest -q \\
|
||||
tests/test_telegram_news_dataset.py
|
||||
|
||||
Ожидаемая корреляция: Telegram-новости имеют URL на ``t.me``, VK-новости —
|
||||
на ``vk.com``, остальные — на других хостах. Любое расхождение означает
|
||||
ошибку классификации. Без файла датасета или без ``ETL_FULL_DATASET_TEST=1``
|
||||
тест пропускается.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from src.pipeline.etl import _should_prepend_title
|
||||
|
||||
DATASET_PATH = Path(__file__).resolve().parents[1] / ".data" / "csv" / "output.csv"
|
||||
|
||||
_TELEGRAM_HOSTS = frozenset({"t.me", "telegram.me", "telegram.org", "telegram.dog"})
|
||||
_VK_HOSTS = frozenset({"vk.com", "vk.ru"})
|
||||
# Значения по умолчанию для TITLE_EXCLUDED_TYPE_IDS.
|
||||
_EXCLUDED_TITLE_TYPE_IDS = frozenset({"2", "3"})
|
||||
_MAX_REPORTED_MISMATCHES = 20
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.slow,
|
||||
pytest.mark.skipif(
|
||||
not DATASET_PATH.exists(),
|
||||
reason=f"Нет файла датасета: {DATASET_PATH}",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _url_host(url: str) -> str:
|
||||
"""Возвращает нормализованный хост URL или пустую строку."""
|
||||
try:
|
||||
host = urlsplit(url.strip()).hostname
|
||||
except ValueError:
|
||||
return ""
|
||||
return (host or "").lower().rstrip(".")
|
||||
|
||||
|
||||
def _is_host(url: str, hosts: frozenset[str]) -> bool:
|
||||
"""Проверяет, что хост URL относится к одному из заданных доменов."""
|
||||
host = _url_host(url)
|
||||
if not host:
|
||||
return False
|
||||
return any(host == known or host.endswith(f".{known}") for known in hosts)
|
||||
|
||||
|
||||
def _is_telegram_url(url: str) -> bool:
|
||||
"""Независимый признак Telegram-источника по хосту URL."""
|
||||
return _is_host(url, _TELEGRAM_HOSTS)
|
||||
|
||||
|
||||
def _is_vk_url(url: str) -> bool:
|
||||
"""Независимый признак VK-источника по хосту URL."""
|
||||
return _is_host(url, _VK_HOSTS)
|
||||
|
||||
|
||||
def _format_mismatch(
|
||||
line_no: int,
|
||||
type_id: str,
|
||||
url: str,
|
||||
resource_id: str,
|
||||
actual_prepend: bool,
|
||||
expected_prepend: bool,
|
||||
) -> str:
|
||||
"""Формирует читаемое описание расхождения для отчёта теста."""
|
||||
return (
|
||||
f"строка {line_no}: type_id={type_id!r}, url={url!r}, "
|
||||
f"resource_id={resource_id!r}, "
|
||||
f"_should_prepend_title={actual_prepend} (ожидалось {expected_prepend})"
|
||||
)
|
||||
|
||||
|
||||
def test_title_source_classification_matches_url_on_full_dataset() -> None:
|
||||
"""Каждая строка выгрузки: предикат совпадает с хостом URL."""
|
||||
if os.getenv("ETL_FULL_DATASET_TEST") != "1":
|
||||
pytest.skip("Полная проверка датасета: задайте ETL_FULL_DATASET_TEST=1")
|
||||
|
||||
csv.field_size_limit(sys.maxsize)
|
||||
|
||||
checked_rows = 0
|
||||
mismatches = 0
|
||||
details: list[str] = []
|
||||
|
||||
with DATASET_PATH.open("r", encoding="utf-8", newline="") as file:
|
||||
reader = csv.reader(file)
|
||||
try:
|
||||
header = next(reader)
|
||||
except StopIteration:
|
||||
pytest.fail(f"Файл датасета пуст: {DATASET_PATH}")
|
||||
|
||||
required = {"type_id", "url", "resource_id"}
|
||||
missing = required.difference(header)
|
||||
if missing:
|
||||
pytest.fail(f"В датасете нет колонок: {sorted(missing)}")
|
||||
|
||||
index = {name: position for position, name in enumerate(header)}
|
||||
type_id_index = index["type_id"]
|
||||
url_index = index["url"]
|
||||
resource_id_index = index["resource_id"]
|
||||
|
||||
for line_no, row in enumerate(reader, start=2):
|
||||
type_id = row[type_id_index].strip()
|
||||
url = row[url_index]
|
||||
resource_id = row[resource_id_index].strip()
|
||||
|
||||
actual_prepend = _should_prepend_title(
|
||||
{"type_id": type_id}, _EXCLUDED_TITLE_TYPE_IDS
|
||||
)
|
||||
expected_prepend = not (_is_telegram_url(url) or _is_vk_url(url))
|
||||
|
||||
if actual_prepend != expected_prepend:
|
||||
mismatches += 1
|
||||
if len(details) < _MAX_REPORTED_MISMATCHES:
|
||||
details.append(
|
||||
_format_mismatch(
|
||||
line_no,
|
||||
type_id,
|
||||
url,
|
||||
resource_id,
|
||||
actual_prepend,
|
||||
expected_prepend,
|
||||
)
|
||||
)
|
||||
|
||||
checked_rows += 1
|
||||
|
||||
assert checked_rows > 0
|
||||
assert mismatches == 0, (
|
||||
f"Расхождений {mismatches} из {checked_rows} строк. "
|
||||
f"Первые {len(details)}:\n" + "\n".join(details)
|
||||
)
|
||||
Reference in new issue
Block a user