| 1 | from __future__ import annotations |
| 2 | |
| 3 | import sys |
| 4 | import tempfile |
| 5 | import time |
| 6 | import unittest |
| 7 | from pathlib import Path |
| 8 | |
| 9 | sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) |
| 10 | |
| 11 | from src import api_engine, config, jobs |
| 12 | from tests.unit.test_extract_formats import docx_bytes, odt_bytes, pptx_bytes |
| 13 | |
| 14 | LONG = "Hucre canliligin temel birimidir. " * 8 |
| 15 | SCHOOL = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d" |
| 16 | |
| 17 | |
| 18 | class MultiSourceTestCase(unittest.TestCase): |
| 19 | def setUp(self) -> None: |
| 20 | self._log_level = config._active_level |
| 21 | config.set_log_level("error") |
| 22 | self._tmp = tempfile.TemporaryDirectory(prefix="coklu-") |
| 23 | self.root = Path(self._tmp.name) |
| 24 | self.media = self.root / "medya" |
| 25 | (self.media / SCHOOL).mkdir(parents=True) |
| 26 | |
| 27 | def tearDown(self) -> None: |
| 28 | self._tmp.cleanup() |
| 29 | config._active_level = self._log_level |
| 30 | |
| 31 | def source(self, key: str, data: bytes) -> Path: |
| 32 | path = self.media / SCHOOL / key |
| 33 | path.write_bytes(data) |
| 34 | return path |
| 35 | |
| 36 | def settings(self): |
| 37 | settings = config.Config(require_token=False) |
| 38 | settings.media_root = str(self.media) |
| 39 | return settings |
| 40 | |
| 41 | |
| 42 | class TheRecordCarriesSources(MultiSourceTestCase): |
| 43 | def make_store(self) -> jobs.JobStore: |
| 44 | store = jobs.JobStore( |
| 45 | root=self.root / "isler", workers=1, max_jobs=64, stage_secs=0.0 |
| 46 | ) |
| 47 | self.addCleanup(store.shutdown, 1.0) |
| 48 | return store |
| 49 | |
| 50 | def test_the_singular_field_stays_the_first_source(self) -> None: |
| 51 | store = self.make_store() |
| 52 | sources = [ |
| 53 | {"key": "bir", "name": "Birinci", "content_type": "application/pdf"}, |
| 54 | {"key": "iki", "name": "Ikinci", "content_type": "text/plain"}, |
| 55 | ] |
| 56 | record, _ = store.submit( |
| 57 | "aaaaaaaa-aaaa-7aaa-8aaa-000000000001", |
| 58 | "not-1", |
| 59 | "duz_okuma", |
| 60 | source_key="bir", |
| 61 | sources=sources, |
| 62 | ) |
| 63 | self.assertEqual(record["source_key"], "bir") |
| 64 | self.assertEqual( |
| 65 | record["sources"], |
| 66 | [ |
| 67 | { |
| 68 | "key": "bir", |
| 69 | "name": "Birinci", |
| 70 | "content_type": "application/pdf", |
| 71 | "status": "pending", |
| 72 | }, |
| 73 | { |
| 74 | "key": "iki", |
| 75 | "name": "Ikinci", |
| 76 | "content_type": "text/plain", |
| 77 | "status": "pending", |
| 78 | }, |
| 79 | ], |
| 80 | ) |
| 81 | |
| 82 | def test_a_legacy_single_key_submit_fills_the_sources_list(self) -> None: |
| 83 | store = self.make_store() |
| 84 | record, _ = store.submit( |
| 85 | "aaaaaaaa-aaaa-7aaa-8aaa-000000000002", |
| 86 | "not-1", |
| 87 | "duz_okuma", |
| 88 | source_key="tek", |
| 89 | ) |
| 90 | self.assertEqual( |
| 91 | record["sources"], |
| 92 | [ |
| 93 | { |
| 94 | "key": "tek", |
| 95 | "name": "tek", |
| 96 | "content_type": "", |
| 97 | "status": "pending", |
| 98 | } |
| 99 | ], |
| 100 | ) |
| 101 | |
| 102 | def test_sources_is_not_a_required_field(self) -> None: |
| 103 | self.assertNotIn( |
| 104 | "sources", |
| 105 | jobs.REQUIRED_FIELDS, |
| 106 | "REQUIRED_FIELDS'a eklenirse alan eklenmeden once yazilmis eski " |
| 107 | "kayitlar acilista topluca atilir", |
| 108 | ) |
| 109 | |
| 110 | def test_an_old_record_without_sources_still_loads(self) -> None: |
| 111 | store = self.make_store() |
| 112 | job_id = "aaaaaaaa-aaaa-7aaa-8aaa-000000000003" |
| 113 | store.submit(job_id, "not-1", "duz_okuma", source_key="eski") |
| 114 | path = Path(store.root) / f"{job_id}.json" |
| 115 | import json |
| 116 | |
| 117 | data = json.loads(path.read_text(encoding="utf-8")) |
| 118 | data.pop("sources", None) |
| 119 | path.write_text(json.dumps(data), encoding="utf-8") |
| 120 | reopened = jobs.JobStore( |
| 121 | root=store.root, workers=1, max_jobs=64, stage_secs=0.0 |
| 122 | ) |
| 123 | self.addCleanup(reopened.shutdown, 1.0) |
| 124 | loaded = reopened.get(job_id) |
| 125 | self.assertEqual(loaded["source_key"], "eski") |
| 126 | context = jobs.JobContext(reopened, job_id) |
| 127 | self.assertEqual( |
| 128 | [item["key"] for item in context.sources], |
| 129 | ["eski"], |
| 130 | "sources alani olmayan eski kayit tekil alandan turetilmeli", |
| 131 | ) |
| 132 | |
| 133 | def test_sources_survive_a_full_job_lifecycle(self) -> None: |
| 134 | store = self.make_store() |
| 135 | store.start() |
| 136 | job_id = "aaaaaaaa-aaaa-7aaa-8aaa-000000000004" |
| 137 | store.submit( |
| 138 | job_id, |
| 139 | "not-1", |
| 140 | "duz_okuma", |
| 141 | school=SCHOOL, |
| 142 | source_key="tek", |
| 143 | sources=[ |
| 144 | {"key": "tek", "name": "Tek", "content_type": "text/plain"} |
| 145 | ], |
| 146 | ) |
| 147 | deadline = time.monotonic() + 10.0 |
| 148 | record = store.get(job_id) |
| 149 | while record["state"] not in jobs.TERMINAL_STATES: |
| 150 | if time.monotonic() > deadline: |
| 151 | self.fail("sahte is zaman asiminda bitmedi") |
| 152 | time.sleep(0.02) |
| 153 | record = store.get(job_id) |
| 154 | self.assertEqual( |
| 155 | record["sources"], |
| 156 | [ |
| 157 | { |
| 158 | "key": "tek", |
| 159 | "name": "Tek", |
| 160 | "content_type": "text/plain", |
| 161 | "status": "pending", |
| 162 | } |
| 163 | ], |
| 164 | ) |
| 165 | |
| 166 | def test_update_sources_needs_a_running_job(self) -> None: |
| 167 | store = self.make_store() |
| 168 | record, _ = store.submit( |
| 169 | "aaaaaaaa-aaaa-7aaa-8aaa-000000000005", |
| 170 | "not-1", |
| 171 | "duz_okuma", |
| 172 | source_key="tek", |
| 173 | ) |
| 174 | self.assertIsNone( |
| 175 | store.update_sources(record["job_id"], record["sources"]), |
| 176 | "kuyruktaki bir isin kaynak durumu guncellenmemeli", |
| 177 | ) |
| 178 | with self.assertRaises(jobs.JobNotFound): |
| 179 | store.update_sources("aaaaaaaa-aaaa-7aaa-8aaa-999999999999", []) |
| 180 | |
| 181 | |
| 182 | class SourcesAreCombinedIntoOneText(MultiSourceTestCase): |
| 183 | def documents(self, *pairs: tuple[str, Path]) -> list[dict]: |
| 184 | return [{"name": name, "path": path} for name, path in pairs] |
| 185 | |
| 186 | def test_three_documents_are_merged_with_per_document_headers(self) -> None: |
| 187 | docs = self.documents( |
| 188 | ("Birinci", self.source("a", docx_bytes([LONG + "birinci"]))), |
| 189 | ("Ikinci", self.source("b", pptx_bytes([[LONG + "ikinci"]]))), |
| 190 | ("Ucuncu", self.source("c", odt_bytes([LONG + "ucuncu"]))), |
| 191 | ) |
| 192 | text, blocks, ocr = api_engine.extract_sources( |
| 193 | docs, self.settings(), lambda: None |
| 194 | ) |
| 195 | self.assertIn("birinci", text) |
| 196 | self.assertIn("ikinci", text) |
| 197 | self.assertIn("ucuncu", text) |
| 198 | self.assertIn("\n\n=== Ikinci ===\n\n", text) |
| 199 | self.assertIn("\n\n=== Ucuncu ===\n\n", text) |
| 200 | self.assertLess(text.index("birinci"), text.index("=== Ikinci ===")) |
| 201 | self.assertLess(text.index("=== Ikinci ==="), text.index("ikinci")) |
| 202 | self.assertLess(text.index("ikinci"), text.index("=== Ucuncu ===")) |
| 203 | self.assertEqual(blocks, 3) |
| 204 | self.assertEqual(ocr, 0) |
| 205 | self.assertEqual( |
| 206 | [item["status"] for item in docs], ["ok", "ok", "ok"] |
| 207 | ) |
| 208 | |
| 209 | def test_the_submitted_order_is_preserved(self) -> None: |
| 210 | docs = self.documents( |
| 211 | ("Alfa", self.source("a", docx_bytes([LONG + "ALFA"]))), |
| 212 | ("Beta", self.source("b", docx_bytes([LONG + "BETA"]))), |
| 213 | ) |
| 214 | text, _, _ = api_engine.extract_sources( |
| 215 | docs, self.settings(), lambda: None |
| 216 | ) |
| 217 | self.assertLess( |
| 218 | text.index("ALFA"), |
| 219 | text.index("BETA"), |
| 220 | "kaynaklar gonderildikleri sirayla birlestirilmeli", |
| 221 | ) |
| 222 | |
| 223 | def test_a_single_source_has_no_header(self) -> None: |
| 224 | path = self.source("a", docx_bytes([LONG])) |
| 225 | docs = self.documents(("Tek", path)) |
| 226 | birlesik = api_engine.extract_sources( |
| 227 | docs, self.settings(), lambda: None |
| 228 | ) |
| 229 | tekil = api_engine.extract_text(str(path), self.settings(), lambda: None) |
| 230 | self.assertEqual(birlesik, tekil) |
| 231 | self.assertNotIn("===", birlesik[0]) |
| 232 | |
| 233 | def test_a_corrupt_source_is_skipped_and_the_rest_continue(self) -> None: |
| 234 | docs = self.documents( |
| 235 | ("Birinci", self.source("a", docx_bytes([LONG + "birinci"]))), |
| 236 | ("Bozuk", self.source("b", b"\x00bozuk veri")), |
| 237 | ("Ucuncu", self.source("c", odt_bytes([LONG + "ucuncu"]))), |
| 238 | ) |
| 239 | text, _, _ = api_engine.extract_sources( |
| 240 | docs, self.settings(), lambda: None |
| 241 | ) |
| 242 | self.assertIn("birinci", text) |
| 243 | self.assertIn("ucuncu", text) |
| 244 | self.assertNotIn("bozuk veri", text) |
| 245 | self.assertEqual( |
| 246 | [item["status"] for item in docs], |
| 247 | ["ok", "skipped:unsupported_source", "ok"], |
| 248 | ) |
| 249 | |
| 250 | def test_a_textless_source_is_skipped_as_no_text_layer(self) -> None: |
| 251 | docs = self.documents( |
| 252 | ("Birinci", self.source("a", docx_bytes([LONG + "birinci"]))), |
| 253 | ("Bos", self.source("b", docx_bytes(["", " "]))), |
| 254 | ) |
| 255 | text, _, _ = api_engine.extract_sources( |
| 256 | docs, self.settings(), lambda: None |
| 257 | ) |
| 258 | self.assertIn("birinci", text) |
| 259 | self.assertEqual( |
| 260 | [item["status"] for item in docs], |
| 261 | ["ok", "skipped:no_text_layer"], |
| 262 | ) |
| 263 | |
| 264 | def test_all_sources_failing_yields_an_empty_merge_with_statuses(self) -> None: |
| 265 | docs = self.documents( |
| 266 | ("Birinci", self.source("a", b"\x00bozuk veri")), |
| 267 | ("Ikinci", self.source("b", docx_bytes(["", ""]))), |
| 268 | ) |
| 269 | text, blocks, ocr = api_engine.extract_sources( |
| 270 | docs, self.settings(), lambda: None |
| 271 | ) |
| 272 | self.assertEqual(text, "") |
| 273 | self.assertEqual(blocks, 0) |
| 274 | self.assertEqual(ocr, 0) |
| 275 | self.assertEqual( |
| 276 | [item["status"] for item in docs], |
| 277 | ["skipped:unsupported_source", "skipped:no_text_layer"], |
| 278 | ) |
| 279 | |
| 280 | def test_no_source_at_all_is_refused(self) -> None: |
| 281 | with self.assertRaises(api_engine.EngineError) as raised: |
| 282 | api_engine.extract_sources([], self.settings(), lambda: None) |
| 283 | self.assertEqual(raised.exception.code, api_engine.SOURCE_NOT_FOUND) |
| 284 | |
| 285 | def test_cancellation_is_checked_between_sources(self) -> None: |
| 286 | docs = self.documents( |
| 287 | ("Birinci", self.source("a", docx_bytes([LONG]))), |
| 288 | ("Ikinci", self.source("b", docx_bytes([LONG]))), |
| 289 | ) |
| 290 | cagrilar = [] |
| 291 | |
| 292 | def check(): |
| 293 | cagrilar.append(1) |
| 294 | if len(cagrilar) > 1: |
| 295 | raise jobs.JobCancelled("iptal") |
| 296 | |
| 297 | with self.assertRaises(jobs.JobCancelled): |
| 298 | api_engine.extract_sources(docs, self.settings(), check) |
| 299 | |
| 300 | |
| 301 | if __name__ == "__main__": |
| 302 | unittest.main() |