|
| 1 | +""" |
| 2 | +we try to fill a database using kohlrahbi[sqlmodels] and the data from the machine-readable AHB submodule |
| 3 | +""" |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | +from typing import Generator |
| 7 | + |
| 8 | +import pytest |
| 9 | +from sqlmodel import Session, SQLModel, create_engine |
| 10 | + |
| 11 | +from fundamend import AhbReader |
| 12 | +from fundamend.models.anwendungshandbuch import Anwendungshandbuch as PydanticAnwendunghandbuch |
| 13 | +from fundamend.sqlmodels.anwendungshandbuch import Anwendungshandbuch as SqlAnwendungshandbuch |
| 14 | + |
| 15 | +from .conftest import is_private_submodule_checked_out |
| 16 | + |
| 17 | + |
| 18 | +@pytest.fixture() |
| 19 | +def sqlite_session(tmp_path: Path) -> Generator[Session, None, None]: |
| 20 | + database_path = tmp_path / "test.db" |
| 21 | + engine = create_engine(f"sqlite:///{database_path}") |
| 22 | + SQLModel.metadata.drop_all(engine) |
| 23 | + SQLModel.metadata.create_all(engine) |
| 24 | + with Session(bind=engine) as session: |
| 25 | + yield session |
| 26 | + session.commit() |
| 27 | + session.flush() |
| 28 | + print(f"Wrote all data to {database_path.absolute()}") |
| 29 | + |
| 30 | + |
| 31 | +def _load_anwendungshandbuch_ahb_to_and_from_db( |
| 32 | + session: Session, pydantic_ahb: PydanticAnwendunghandbuch |
| 33 | +) -> PydanticAnwendunghandbuch: |
| 34 | + sql_ahb = SqlAnwendungshandbuch.from_model(pydantic_ahb) |
| 35 | + session.add(sql_ahb) |
| 36 | + session.commit() |
| 37 | + session.refresh(sql_ahb) |
| 38 | + pydantic_ahb_after_roundtrip = sql_ahb.to_model() |
| 39 | + return pydantic_ahb_after_roundtrip |
| 40 | + |
| 41 | + |
| 42 | +def test_sqlmodels_single_anwendungshandbuch(sqlite_session: Session) -> None: |
| 43 | + ahb = AhbReader( |
| 44 | + Path(__file__).parent / "example_files" / "UTILTS_AHB_1.1d_Konsultationsfassung_2024_04_02.xml" |
| 45 | + ).read() |
| 46 | + roundtrip_abb = _load_anwendungshandbuch_ahb_to_and_from_db(sqlite_session, ahb) |
| 47 | + ahb_json = ahb.model_dump(mode="json") |
| 48 | + roundtrip_json = roundtrip_abb.model_dump(mode="json") |
| 49 | + assert ahb_json == roundtrip_json # in pycharm the error message is much better when comparing plain python dicts |
| 50 | + assert roundtrip_abb == ahb |
| 51 | + |
| 52 | + |
| 53 | +def test_sqlmodels_all_anwendungshandbuch(sqlite_session: Session) -> None: |
| 54 | + if not is_private_submodule_checked_out(): |
| 55 | + pytest.skip("Skipping test because of missing private submodule") |
| 56 | + private_submodule_root = Path(__file__).parent.parent / "xml-migs-and-ahbs" |
| 57 | + assert private_submodule_root.exists() and private_submodule_root.is_dir() |
| 58 | + for ahb_file_path in private_submodule_root.rglob("**/*AHB*.xml"): |
| 59 | + ahb = AhbReader(ahb_file_path).read() |
| 60 | + roundtrip_abb = _load_anwendungshandbuch_ahb_to_and_from_db(sqlite_session, ahb) |
| 61 | + assert roundtrip_abb == ahb |
0 commit comments