|
| 1 | +"""Tests for concurrent XML loading with multiprocessing and a file-based DuckDB.""" |
| 2 | +import multiprocessing |
| 3 | +import os |
| 4 | +import tempfile |
| 5 | + |
| 6 | +import pytest |
| 7 | +from lxml import etree |
| 8 | + |
| 9 | +pytest.importorskip("duckdb", reason="duckdb not installed") |
| 10 | + |
| 11 | +from sqlalchemy import String, create_engine, text |
| 12 | + |
| 13 | +from xml2db import DataModel |
| 14 | + |
| 15 | +_SAMPLE = os.path.join(os.path.dirname(__file__), "sample_models", "orders") |
| 16 | +_XSD = os.path.join(_SAMPLE, "orders.xsd") |
| 17 | +_XML_FILES = [ |
| 18 | + os.path.join(_SAMPLE, "xml", f"order{i}.xml") for i in (1, 2, 3) |
| 19 | +] |
| 20 | + |
| 21 | +# Matches orders model version 0 in sample_models/models.py so that the XML |
| 22 | +# roundtrip produces byte-for-byte identical output. |
| 23 | +_MODEL_CONFIG = { |
| 24 | + "tables": { |
| 25 | + "shiporder": {"fields": {"orderperson": {"transform": False}}}, |
| 26 | + "item": None, |
| 27 | + }, |
| 28 | + "record_hash_column_name": "record_hash", |
| 29 | + "metadata_columns": [ |
| 30 | + {"name": "input_file_path", "type": String(256)}, |
| 31 | + ], |
| 32 | +} |
| 33 | + |
| 34 | + |
| 35 | +def _load_xml_file(xml_path: str, xsd_path: str, db_path: str, lock) -> None: |
| 36 | + """Worker function: parse one XML file and load it into a shared DuckDB file. |
| 37 | +
|
| 38 | + Each process builds its own DataModel (and gets a unique temp_prefix UUID), |
| 39 | + so temporary tables never collide. All database I/O is serialised via *lock* |
| 40 | + because DuckDB allows only one active writer at a time. |
| 41 | + """ |
| 42 | + model = DataModel( |
| 43 | + xsd_file=xsd_path, |
| 44 | + connection_string=f"duckdb:///{db_path}", |
| 45 | + model_config=_MODEL_CONFIG, |
| 46 | + ) |
| 47 | + # CPU-bound XML parsing runs in parallel across processes. |
| 48 | + doc = model.parse_xml(xml_path, metadata={"input_file_path": xml_path}) |
| 49 | + |
| 50 | + # Serialise all database access: one writer at a time for DuckDB. |
| 51 | + with lock: |
| 52 | + doc.insert_into_target_tables() |
| 53 | + # Dispose inside the lock so the file handle is released before |
| 54 | + # the next process tries to open the database. |
| 55 | + model.engine.dispose() |
| 56 | + |
| 57 | + |
| 58 | +def test_multiprocessing_file_duckdb(): |
| 59 | + """Three worker processes load XML files concurrently into a file-based DuckDB. |
| 60 | +
|
| 61 | + Parsing happens in parallel; database writes are serialised via a |
| 62 | + multiprocessing.Lock. After all workers finish: |
| 63 | + - the target table must contain one row per XML file, and |
| 64 | + - each file must round-trip back to identical XML (content assertion). |
| 65 | + """ |
| 66 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 67 | + db_path = os.path.join(tmpdir, "test.duckdb") |
| 68 | + lock = multiprocessing.Lock() |
| 69 | + |
| 70 | + processes = [ |
| 71 | + multiprocessing.Process( |
| 72 | + target=_load_xml_file, |
| 73 | + args=(xml_path, _XSD, db_path, lock), |
| 74 | + ) |
| 75 | + for xml_path in _XML_FILES |
| 76 | + ] |
| 77 | + for p in processes: |
| 78 | + p.start() |
| 79 | + for p in processes: |
| 80 | + p.join() |
| 81 | + assert p.exitcode == 0, ( |
| 82 | + f"Worker for {_XML_FILES[processes.index(p)]} " |
| 83 | + f"exited with code {p.exitcode}" |
| 84 | + ) |
| 85 | + |
| 86 | + # --- row count --- |
| 87 | + engine = create_engine(f"duckdb:///{db_path}") |
| 88 | + with engine.connect() as conn: |
| 89 | + count = conn.execute(text("SELECT COUNT(*) FROM orders")).scalar() |
| 90 | + engine.dispose() |
| 91 | + assert count == len(_XML_FILES) |
| 92 | + |
| 93 | + # --- content roundtrip --- |
| 94 | + verify_model = DataModel( |
| 95 | + xsd_file=_XSD, |
| 96 | + connection_string=f"duckdb:///{db_path}", |
| 97 | + model_config=_MODEL_CONFIG, |
| 98 | + ) |
| 99 | + for xml_path in _XML_FILES: |
| 100 | + doc = verify_model.extract_from_database( |
| 101 | + f"input_file_path='{xml_path}'", |
| 102 | + force_tz="Europe/Paris", |
| 103 | + ) |
| 104 | + src = etree.parse(xml_path).getroot() |
| 105 | + el = doc.to_xml(nsmap=src.nsmap) |
| 106 | + for key, val in src.attrib.items(): |
| 107 | + el.set(key, val) |
| 108 | + actual = etree.tostring( |
| 109 | + el, pretty_print=True, encoding="utf-8", xml_declaration=True |
| 110 | + ).decode("utf-8") |
| 111 | + with open(xml_path) as f: |
| 112 | + expected = f.read() |
| 113 | + assert actual == expected, f"XML roundtrip failed for {xml_path}" |
| 114 | + verify_model.engine.dispose() |
0 commit comments