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