"""Options that let one document source cope with however its rows are stored: columns carried through as field values, a column grouping rows into records, filters that pick which documents feed a target, documents kept as hex or base64 text, unreadable rows, and queries that a derived table can't hold as written. Fixtures: `client` (the app wired to a fresh CaCu database) and `documents_table`, a SQLite table built per test whose rows carry two reports of one order, a third report of the same patient under another order, and an unrelated kind of report. """ import base64 import pytest from sqlalchemy import create_engine, text from extraction.testing import text_pdf from webapi.imports.connectors.document import document_bytes from webapi.imports.connectors.sql import SqlConnector, _without_trailing_order_by @pytest.fixture(scope="module") def client(wire_domain): wire_domain("cacu") from webapi import create_app app = create_app() app.config.update(TESTING=True) with app.test_client() as test_client: yield test_client @pytest.fixture def documents_table(tmp_path): """Rows 1 and 2 are two reports of order 10 of patient P-1, row 3 is a report of order 11 of the same patient, and row 4 is a report of a kind the CaCu cytology target doesn't take. No body prints the patient id the structured columns hold.""" url = f"sqlite:///{tmp_path / 'docs.db'}" rows = [ (1, "P-1", 10, "Prueba de VPH\nVPH alto riesgo: POSITIVO"), (2, "P-1", 10, "Prueba de VPH\nGenotipo 18: DETECTADO"), (3, "P-1", 11, "Prueba de VPH\nVPH alto riesgo: NEGATIVO"), (4, "P-1", 12, "Informe de otra especialidad\nSin datos de VPH"), ] with create_engine(url).begin() as conn: conn.execute(text("CREATE TABLE docs (row_id INTEGER, patient INTEGER, order_ref INTEGER, body TEXT)")) for row in rows: conn.execute(text("INSERT INTO docs VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row))) return url def _payload(url: str, **sql) -> dict: base = {"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"} return {"sql": {**base, **sql}, "target": "cacu.CitologiaCervical"} def _extract(client, payload: dict) -> dict: response = client.post("/imports/sources/document/extract", json=payload) assert response.status_code == 200, response.get_json() return response.get_json() def test_group_column_keeps_orders_apart_and_merges_within_one(client, documents_table): """Rows sharing `group_column` become one record; the same patient's other order stays its own record. Fails if `group_column` stops reaching `record_keys`.""" body = _extract( client, _payload( documents_table, fields={"pac_id_hospital": "patient", "ord_numero_hospital": "order_ref"}, group_column="order_ref", ) | {"exclude_pattern": "otra especialidad"}, ) by_key = {record["key"]: record for record in body["records"]} assert set(by_key) == {"10", "11"} assert by_key["10"]["fields"]["cit_vph_genotipo_18"]["value"] == 1 assert by_key["11"]["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO" assert by_key["10"]["fields"]["pac_id_hospital"]["value"] == "P-1" def test_filters_leave_out_other_kinds_of_report_and_say_so(client, documents_table): """`include_pattern` keeps only matching documents, matched without regard to case or accents, and the rest are listed as skipped. Fails if the filters stop applying or `skipped` stops reporting them.""" body = _extract( client, _payload(documents_table, fields={"pac_id_hospital": "patient"}) | {"include_pattern": "prueba de vph"}, ) assert [skipped["document"] for skipped in body["skipped"]] == ["4"] def test_a_filter_that_matches_nothing_is_an_error(client, documents_table): """Filtering out every document is reported instead of returning an empty import. Fails if `_extract` stops refusing an empty selection.""" response = client.post( "/imports/sources/document/extract", json=_payload(documents_table) | {"include_pattern": "no aparece"} ) assert response.status_code == 400 def test_an_invalid_filter_is_a_bad_request(client, documents_table): """A filter that isn't a valid regular expression is rejected with a message naming it. Fails if `_compile_filter` lets `re.error` through.""" response = client.post("/imports/sources/document/extract", json=_payload(documents_table) | {"exclude_pattern": "("}) assert response.status_code == 400 and "exclude_pattern" in response.get_json()["error"] def test_documents_stored_as_hex_or_base64_text_are_decoded(): """A PDF kept in a text column as hex (with or without `0x`) or base64 reaches the readers as the PDF itself, and ordinary text stays text. Fails if `document_bytes` stops recognizing either encoding.""" pdf = text_pdf([["Expediente: X-1"]]) assert document_bytes("0x" + pdf.hex()) == pdf assert document_bytes(pdf.hex().upper()) == pdf assert document_bytes(base64.b64encode(pdf).decode()) == pdf assert document_bytes("Expediente: X-1") == b"Expediente: X-1" def test_an_unreadable_row_is_skipped_not_fatal(client, tmp_path): """One corrupt document among readable ones is listed as skipped while the rest are extracted. Fails if a single unreadable row aborts the whole source again.""" url = f"sqlite:///{tmp_path / 'mixed.db'}" with create_engine(url).begin() as conn: conn.execute(text("CREATE TABLE docs (row_id INTEGER, body BLOB)")) conn.execute(text("INSERT INTO docs VALUES (1, :b)"), {"b": b"%PDF-1.4 truncated"}) conn.execute(text("INSERT INTO docs VALUES (2, :b)"), {"b": text_pdf([["Expediente: X-2", "VPH alto riesgo: POSITIVO"]])}) body = _extract(client, _payload(url)) assert [record["key"] for record in body["records"]] == ["X-2"] assert [skipped["document"] for skipped in body["skipped"]] == ["1"] def test_repeated_key_column_values_still_name_rows_apart(tmp_path): """Two rows with the same `key_column` value get distinct names, so neither one's fields or pages overwrite the other's. Fails if `_files_from_sql` stops suffixing repeated names.""" from webapi.imports.connectors.document import _files_from_sql url = f"sqlite:///{tmp_path / 'r.db'}" with create_engine(url).begin() as conn: conn.execute(text("CREATE TABLE docs (row_id INTEGER, body TEXT)")) conn.execute(text("INSERT INTO docs VALUES (7, 'uno'), (7, 'dos')")) documents = _files_from_sql({"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"}) assert [name for name, _ in documents.files] == ["7", "7#2"] @pytest.mark.parametrize( "query,kept", [ ("SELECT a FROM t ORDER BY a", "SELECT a FROM t"), ("SELECT TOP 5 a FROM t ORDER BY a", None), ("SELECT a FROM t ORDER BY a OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", None), ("SELECT a, (SELECT TOP 1 b FROM u ORDER BY b) AS x FROM t", None), ("SELECT 'ORDER BY' AS s FROM t ORDER BY s", "SELECT 'ORDER BY' AS s FROM t"), ], ) def test_an_unlimited_trailing_order_by_is_dropped_before_wrapping(query, kept): """SQL Server refuses `ORDER BY` inside a derived table unless TOP or OFFSET goes with it, so one that only sorts is dropped; one that picks rows, or sits inside a subquery or a string, stays. Fails if `_without_trailing_order_by` drops an `ORDER BY` that chooses rows or keeps one that would make the wrapped query invalid.""" assert _without_trailing_order_by(query, "mssql") == (kept or query) def test_a_named_instance_or_embedded_port_reaches_the_driver(): """`host\\instance` leaves the port unset for the server to resolve, and `host,port` or `host:port` fill it in. Fails if `server_url` stops parsing addresses or goes back to forcing the default port on a named instance.""" named = SqlConnector.server_url({"engine": "mssql", "host": "db.example\\INST", "database": "d"}) assert (named.host, named.port) == ("db.example\\INST", None) comma = SqlConnector.server_url({"engine": "mssql", "host": "db.example,1500", "database": "d"}) assert (comma.host, comma.port) == ("db.example", 1500) colon = SqlConnector.server_url({"engine": "postgresql", "host": "db.example:6543", "database": "d"}) assert (colon.host, colon.port) == ("db.example", 6543)