ativa-ia/tests/test_atvctl_ingest.py

297 lines
12 KiB
Python

import hashlib
import zipfile
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "bin"))
import atvctl_ingest as ingest
class FakeResponse:
def __init__(self, result, wrap=True):
self._result = result
self._wrap = wrap
self.status_code = 200
def raise_for_status(self):
return None
def json(self):
return {"result": self._result} if self._wrap else self._result
class FakeSession:
def __init__(self):
self.points = {}
self.upsert_calls = []
self.delete_calls = []
self.embedding_calls = []
self.read_calls = []
def get(self, url, timeout):
self.read_calls.append(("GET", url))
return FakeResponse({
"config": {"params": {"vectors": {"size": 768, "distance": "Cosine"}}}
})
def post(self, url, json, timeout, params=None):
if url.endswith("/points/scroll"):
self.read_calls.append(("SCROLL", url))
points = sorted(self.points.values(), key=lambda point: str(point["id"]))
return FakeResponse({"points": points, "next_page_offset": None})
if url.endswith("/api/embed"):
self.embedding_calls.append(list(json["input"]))
vectors = [[float(len(text))] * ingest.VECTOR_SIZE for text in json["input"]]
return FakeResponse({"embeddings": vectors}, wrap=False)
if url.endswith("/points/delete"):
ids = list(json["points"])
self.delete_calls.append(ids)
for point_id in ids:
self.points.pop(str(point_id), None)
return FakeResponse({"status": "completed"})
raise AssertionError(f"POST inesperado: {url}")
def put(self, url, json, timeout, params=None):
if not url.endswith("/points"):
raise AssertionError(f"PUT inesperado: {url}")
points = list(json["points"])
self.upsert_calls.append(points)
for point in points:
self.points[str(point["id"])] = point
return FakeResponse({"status": "completed"})
class IngestTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.root = Path(self.temp.name)
self.session = FakeSession()
def tearDown(self):
self.temp.cleanup()
def run_sync(self, mode):
return ingest.synchronize(
self.root,
self.session,
"http://qdrant.test",
"http://ollama.test",
"nomic-embed-text",
"ativa_knowledge",
mode,
)
def test_chunking_has_expected_overlap(self):
text = "a" * 1500
chunks = ingest.chunk_text(text)
self.assertEqual(len(chunks), 2)
self.assertEqual(chunks[0][-ingest.OVERLAP:], chunks[1][:ingest.OVERLAP])
def test_dry_run_reports_new_without_any_write_or_embedding(self):
(self.root / "a.md").write_text("conteúdo inicial", encoding="utf-8")
plan = self.run_sync("dry-run")
self.assertEqual([item.status for item in plan], ["new"])
self.assertEqual(self.session.upsert_calls, [])
self.assertEqual(self.session.delete_calls, [])
self.assertEqual(self.session.embedding_calls, [])
self.assertEqual(self.session.points, {})
def test_apply_is_idempotent_updates_and_removes_stale_chunks(self):
source = self.root / "a.md"
source.write_text("a" * 1500, encoding="utf-8")
other = self.root / "other.md"
other.write_text("outro documento", encoding="utf-8")
first = self.run_sync("apply")
self.assertEqual([item.status for item in first], ["new", "new"])
self.assertEqual(len(self.session.points), 3)
first_ids = set(self.session.points)
self.assertEqual(len({p["payload"]["document_id"] for p in self.session.points.values()}), 2)
second = self.run_sync("apply")
self.assertEqual([item.status for item in second], ["unchanged", "unchanged"])
self.assertEqual(set(self.session.points), first_ids)
self.assertEqual(len(self.session.upsert_calls), 2)
source.write_text("texto novo e curto", encoding="utf-8")
changed = self.run_sync("apply")
self.assertEqual([item.status for item in changed], ["modified", "unchanged"])
self.assertEqual(len(self.session.points), 2)
changed_point = next(
point for point in self.session.points.values()
if point["payload"]["source"] == "a.md"
)
self.assertEqual(changed_point["payload"]["text"], "texto novo e curto")
self.assertEqual(changed_point["payload"]["managed_by"], "atvctl")
source.unlink()
removed = self.run_sync("apply")
self.assertEqual(
[(item.relative, item.status) for item in removed],
[("other.md", "unchanged"), ("a.md", "removed")],
)
self.assertEqual(len(self.session.points), 1)
self.assertEqual(
next(iter(self.session.points.values()))["payload"]["source"],
"other.md",
)
def test_identical_content_in_distinct_paths_does_not_collide(self):
(self.root / "a").mkdir()
(self.root / "b").mkdir()
(self.root / "a" / "doc.md").write_text("mesmo conteúdo", encoding="utf-8")
(self.root / "b" / "doc.md").write_text("mesmo conteúdo", encoding="utf-8")
plan = self.run_sync("apply")
self.assertEqual([item.status for item in plan], ["new", "new"])
self.assertEqual(len(self.session.points), 2)
ids = {point["payload"]["document_id"] for point in self.session.points.values()}
self.assertEqual(len(ids), 2)
def test_previous_atvctl_ids_are_migrated_after_new_upsert(self):
source = self.root / "legacy.md"
text = "conteúdo antigo"
source.write_text(text, encoding="utf-8")
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
old_id = ingest.legacy_point_id(digest, 0)
self.session.points[old_id] = {
"id": old_id,
"payload": {
"source": "legacy.md",
"path": "legacy.md",
"sha256": digest,
"chunk_index": 0,
"embedding_model": "nomic-embed-text",
},
}
plan = self.run_sync("apply")
self.assertEqual([item.status for item in plan], ["modified"])
self.assertNotIn(old_id, self.session.points)
self.assertEqual(len(self.session.points), 1)
self.assertEqual(
next(iter(self.session.points.values()))["payload"]["document_id"],
ingest.stable_document_id("legacy.md"),
)
def test_empty_root_fails_closed(self):
with self.assertRaises(ingest.IngestError):
self.run_sync("apply")
self.assertEqual(self.session.upsert_calls, [])
self.assertEqual(self.session.delete_calls, [])
def test_supported_plain_and_html_formats_preserve_sections(self):
(self.root / "nota.txt").write_text("Texto simples", encoding="utf-8")
(self.root / "pagina.html").write_text(
"<html><body><h1>Atendimento</h1><p>Horário da recepção.</p>"
"<script>segredo que não deve ser indexado</script></body></html>",
encoding="utf-8",
)
documents = ingest.discover_documents(self.root)
self.assertEqual([document.relative for document in documents], ["nota.txt", "pagina.html"])
html_doc = documents[1]
self.assertIn("Horário da recepção", html_doc.chunks[0])
self.assertNotIn("segredo", " ".join(html_doc.chunks))
self.assertEqual(html_doc.chunk_metadata[0]["section"], "Atendimento")
def test_docx_and_xlsx_extract_text_and_section_metadata(self):
docx = self.root / "manual.docx"
with zipfile.ZipFile(docx, "w") as archive:
archive.writestr(
"word/document.xml",
"""<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body><w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr>
<w:r><w:t>Cadastro</w:t></w:r></w:p><w:p><w:r><w:t>Dados necessários</w:t></w:r></w:p>
</w:body></w:document>""",
)
xlsx = self.root / "dados.xlsx"
with zipfile.ZipFile(xlsx, "w") as archive:
archive.writestr(
"xl/workbook.xml",
"""<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets><sheet name="Unidades" sheetId="1" r:id="rId1"/></sheets></workbook>""",
)
archive.writestr(
"xl/_rels/workbook.xml.rels",
"""<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>""",
)
archive.writestr(
"xl/worksheets/sheet1.xml",
"""<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Unidade A</t></is></c>
<c r="B1" t="inlineStr"><is><t>Centro</t></is></c></row></sheetData></worksheet>""",
)
documents = ingest.discover_documents(self.root)
by_name = {document.relative: document for document in documents}
self.assertIn("Dados necessários", " ".join(by_name["manual.docx"].chunks))
self.assertEqual(by_name["manual.docx"].chunk_metadata[0]["section"], "Cadastro")
self.assertIn("Unidade A | Centro", " ".join(by_name["dados.xlsx"].chunks))
self.assertEqual(by_name["dados.xlsx"].chunk_metadata[0]["section"], "Unidades")
@patch.object(ingest.subprocess, "run")
def test_pdf_pages_are_preserved_as_chunk_metadata(self, run):
run.return_value.stdout = "Página um\fPágina dois\f"
run.return_value.check_returncode = lambda: None
(self.root / "manual.pdf").write_bytes(b"%PDF-mock")
document = ingest.discover_documents(self.root)[0]
self.assertEqual(document.chunks, ("Página um", "Página dois"))
self.assertEqual([item["page"] for item in document.chunk_metadata], [1, 2])
def test_unsupported_only_root_fails_closed(self):
(self.root / "imagem.png").write_bytes(b"not indexed")
with self.assertRaisesRegex(ingest.IngestError, "Formatos não suportados"):
ingest.discover_documents(self.root)
def test_mixed_supported_and_unsupported_files_fail_before_partial_plan(self):
(self.root / "documento.md").write_text("conteúdo válido", encoding="utf-8")
(self.root / "imagem.png").write_bytes(b"not indexed")
with self.assertRaisesRegex(ingest.IngestError, "imagem.png"):
self.run_sync("dry-run")
self.assertEqual(self.session.upsert_calls, [])
self.assertEqual(self.session.delete_calls, [])
def test_file_type_version_and_status_are_written_to_qdrant_payload(self):
(self.root / "nota.txt").write_text("Texto indexável", encoding="utf-8")
self.run_sync("apply")
payload = next(iter(self.session.points.values()))["payload"]
self.assertEqual(payload["file_type"], "txt")
self.assertEqual(payload["document_version"], payload["document_hash"][:16])
self.assertEqual(payload["document_status"], "active")
self.assertRegex(payload["indexed_at"], r"^\d{4}-\d\d-\d\dT.*\+00:00$")
def test_unowned_points_are_preserved(self):
(self.root / "a.md").write_text("conteúdo novo", encoding="utf-8")
self.session.points["foreign-id"] = {
"id": "foreign-id",
"payload": {"source": "a.md", "text": "outro fluxo"},
}
self.run_sync("apply")
self.assertIn("foreign-id", self.session.points)
self.assertEqual(len(self.session.points), 2)
if __name__ == "__main__":
unittest.main()