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
|
||||
Reference in new issue
Block a user