Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 87 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,18 @@ def table_of(model: Any) -> sa.Table:
return table


@pytest.fixture
def fresh_cdm_engine(
fresh_engine: sa.Engine,
fresh_resolved: ResolvedCDMDatabase,
tmp_path_factory: pytest.TempPathFactory,
) -> sa.Engine:
"""fresh_engine with every CDM table created and the fixture vocabulary loaded."""
bootstrap(fresh_resolved, create=True)
_load_fixture_vocabulary(fresh_engine, tmp_path_factory.mktemp("fresh-vocabulary"))
return fresh_engine


@pytest.fixture
def fresh_resolved(fresh_db: IsolatedTestDatabase) -> ResolvedCDMDatabase:
"""fresh_db's ResolvedCDMDatabase, for maintenance functions that require one."""
Expand Down Expand Up @@ -436,8 +448,77 @@ def _concept_id(
return int(concept_id)


def add_concepts(session: Session, *concept_ids: int) -> None:
"""Insert a minimal concept for each id the database does not hold yet.

Notes
-----
The concepts use a domain, vocabulary and concept class from the fixture
vocabulary, which the session must already contain.
"""
wanted = set(concept_ids)
held = set(session.scalars(sa.select(Concept.concept_id).where(Concept.concept_id.in_(wanted))))
session.add_all(
Concept(
concept_id=concept_id,
concept_name=f"fixture concept {concept_id}",
domain_id="Condition",
vocabulary_id="SNOMED",
concept_class_id="Clinical Finding",
concept_code=f"fixture-{concept_id}",
valid_start_date=date(1970, 1, 1),
valid_end_date=date(2099, 12, 31),
)
for concept_id in sorted(wanted - held)
)
session.flush()


def seed_row_parents(engine: sa.Engine, *rows: dict[str, Any]) -> None:
"""Insert the persons and concepts that raw table rows reference.

Parameters
----------
engine : sqlalchemy.Engine
Engine of a database holding the CDM tables and the fixture vocabulary.
*rows : dict[str, Any]
Rows keyed by column name. Every ``person_id`` and every column ending
in ``_concept_id`` names a parent that is inserted if missing.
"""
person_ids = {row["person_id"] for row in rows if "person_id" in row}
concept_ids = {
value
for row in rows
for column, value in row.items()
if column.endswith("_concept_id") and value is not None
}
with so.Session(engine) as session:
add_concepts(session, *concept_ids)
held = set(
session.scalars(sa.select(Person.person_id).where(Person.person_id.in_(person_ids)))
)
session.add_all(
Person(
person_id=person_id,
year_of_birth=1980,
gender_concept_id=0,
race_concept_id=0,
ethnicity_concept_id=0,
)
for person_id in sorted(person_ids - held)
)
session.commit()


def _seed_basic_clinical_data(session: Session) -> None:
"""Insert a compact clinical graph used by core model relationship tests."""
"""Insert a compact clinical graph used by core model relationship tests.

Notes
-----
Each row is flushed before the rows that reference it. The models declare
no relationships between these tables, so the session does not order the
inserts and a database that enforces foreign keys refuses a child sent first.
"""
male_concept_id = _concept_id(session, concept_name="MALE", domain_id="Gender")
race_concept_id = _concept_id(session, concept_name="White", domain_id="Race")
ethnicity_concept_id = _concept_id(
Expand Down Expand Up @@ -466,6 +547,7 @@ def _seed_basic_clinical_data(session: Session) -> None:
person_source_value="fixture-person-1",
)
)
session.flush()
session.add(
Observation_Period(
observation_period_id=1,
Expand All @@ -475,6 +557,7 @@ def _seed_basic_clinical_data(session: Session) -> None:
period_type_concept_id=type_concept_id,
)
)
session.flush()
session.add(
Condition_Occurrence(
condition_occurrence_id=1,
Expand All @@ -486,6 +569,7 @@ def _seed_basic_clinical_data(session: Session) -> None:
condition_source_value="fixture-condition-1",
)
)
session.flush()
session.add(
Episode(
episode_id=100,
Expand All @@ -498,6 +582,7 @@ def _seed_basic_clinical_data(session: Session) -> None:
episode_source_value="fixture-parent-episode",
)
)
session.flush()
session.add(
Episode(
episode_id=101,
Expand All @@ -511,6 +596,7 @@ def _seed_basic_clinical_data(session: Session) -> None:
episode_source_value="fixture-child-episode",
)
)
session.flush()
session.add(
Episode_Event(
episode_id=101,
Expand Down
2 changes: 2 additions & 0 deletions tests/test_concept_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
resolve_concept_group,
)
from omop_alchemy.toolkit.core.concepts.registry import ConceptGroupRegistry
from tests.conftest import add_concepts


@dataclass
Expand Down Expand Up @@ -119,6 +120,7 @@ def test_semantic_unit_reference_rejects_empty_paths(value_set: str, unit: str):


def _ancestry(session, pairs):
add_concepts(session, *{concept_id for pair in pairs for concept_id in pair})
session.execute(
ANC.insert(),
[
Expand Down
36 changes: 35 additions & 1 deletion tests/test_concept_mapping_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
from datetime import date

import pytest
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql, sqlite

from omop_alchemy.cdm.model.vocabulary import Concept, Concept_Relationship
from omop_alchemy.cdm.model.vocabulary import Concept, Concept_Relationship, Relationship
from omop_alchemy.toolkit.core.concepts import (
STANDARD_CONCEPT_MAPPING_UNIQUENESS,
StandardConceptMappingSpec,
Expand Down Expand Up @@ -61,7 +62,40 @@ def _relationship(
)


def _add_relationships(session) -> None:
"""Insert the relationships the rows below use, each beside its reverse.

Notes
-----
A relationship names its reverse, so the two rows reference each other. One
multi-row statement is checked once all its rows exist, which two separate
inserts would not satisfy.
"""
names = (
("Maps to", "Mapped from"),
("Mapped from", "Maps to"),
("Maps to value", "Value mapped from"),
("Value mapped from", "Maps to value"),
)
session.execute(
sa.insert(Relationship).values(
[
{
"relationship_id": name,
"relationship_name": name,
"is_hierarchical": 0,
"defines_ancestry": 0,
"reverse_relationship_id": reverse,
"relationship_concept_id": 0,
}
for name, reverse in names
]
)
)


def _add_vocabulary_rows(session) -> None:
_add_relationships(session)
session.add_all(
(
_concept(SOURCE_ID, "source", standard_concept=None),
Expand Down
45 changes: 21 additions & 24 deletions tests/test_modifier_projections.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import sqlalchemy as sa
import sqlalchemy.orm as so
from oa_configurator import Role
from orm_loader.helpers import Base
from sqlalchemy.dialects import postgresql, sqlite

from omop_alchemy.cdm.base import (
Expand Down Expand Up @@ -55,7 +54,7 @@
ValuedModifierRow,
)
from omop_alchemy.toolkit.core.modifiers.projections import _VALUE_COLUMN_TYPES
from tests.conftest import table_of
from tests.conftest import seed_row_parents, table_of

# The full projection shape, in UNION position order. Only the tests need the
# whole; production code asks for the obligation it actually cares about.
Expand Down Expand Up @@ -249,7 +248,7 @@ def test_a_source_naming_a_missing_link_column_is_rejected():


@pytest.mark.parametrize("source_model", [MeasurementView, ObservationView])
def test_modifier_source_subclass_projects_its_own_event_metadata(source_model, fresh_engine):
def test_modifier_source_subclass_projects_its_own_event_metadata(source_model, fresh_cdm_engine):
original = clinical_event_model_spec(source_model)
assert original.event_datetime_column is not None
specialized = type(
Expand Down Expand Up @@ -278,20 +277,18 @@ def test_modifier_source_subclass_projects_its_own_event_metadata(source_model,
assert spec.event_date_column == "projected_date"
assert spec.event_datetime_column == "projected_datetime"

engine = fresh_engine
Base.metadata.create_all(engine, tables=[source_model.__table__])
engine = fresh_cdm_engine
source_row = {
original.event_id_column: 7,
"person_id": 101,
original.event_concept_id_column: 900_001,
original.event_date_column: date(2026, 1, 20),
source_model.__type_concept_id_col__: 32817,
"value_as_concept_id": 900_002,
}
seed_row_parents(engine, source_row)
with engine.begin() as connection:
connection.execute(
source_model.__table__.insert(),
{
original.event_id_column: 7,
"person_id": 101,
original.event_concept_id_column: 900_001,
original.event_date_column: date(2026, 1, 20),
source_model.__type_concept_id_col__: 32817,
"value_as_concept_id": 900_002,
},
)
connection.execute(source_model.__table__.insert(), source_row)
row = connection.execute(canonical_modifier_projection(specialized)).mappings().one()
engine.dispose()

Expand Down Expand Up @@ -364,8 +361,8 @@ def test_target_resolution_queries_compile_for_supported_models(target):


def _seeded_engine(engine, conditions, measurements):
"""Populate fresh_engine with the given condition and measurement rows."""
Base.metadata.create_all(engine, tables=[table_of(Condition_Occurrence), table_of(Measurement)])
"""Populate a fresh CDM database with the given condition and measurement rows."""
seed_row_parents(engine, *conditions, *measurements)
with engine.begin() as connection:
connection.execute(table_of(Condition_Occurrence).insert(), conditions)
connection.execute(table_of(Measurement).insert(), measurements)
Expand Down Expand Up @@ -402,26 +399,26 @@ def _diagnostic_codes(engine, target) -> set[tuple[int, str]]:
return {(row["modifier_id"], row["diagnostic_code"]) for row in rows}


def test_a_whole_target_table_can_prove_a_dangling_modifier(fresh_engine):
def test_a_whole_target_table_can_prove_a_dangling_modifier(fresh_cdm_engine):
"""Absence from an entire table does mean the target row does not exist."""
engine = _seeded_engine(
fresh_engine,
fresh_cdm_engine,
conditions=[_condition(1, 10)],
measurements=[_modifier_of(100, 10, 1), _modifier_of(101, 10, 99)],
)

assert _diagnostic_codes(engine, Condition_Occurrence) == {(101, "missing_target_event")}


def test_a_filtered_target_never_reports_a_missing_target_event(fresh_engine):
def test_a_filtered_target_never_reports_a_missing_target_event(fresh_cdm_engine):
"""A narrowed target set cannot distinguish a defect from its own filter.

Both modifiers below point at conditions that genuinely exist. Reporting
the excluded one as missing would turn the caller's filter into a false
data-quality defect for downstream baseline counts.
"""
engine = _seeded_engine(
fresh_engine,
fresh_cdm_engine,
conditions=[_condition(1, 10), _condition(2, 10)],
measurements=[_modifier_of(100, 10, 1), _modifier_of(101, 10, 2)],
)
Expand All @@ -432,10 +429,10 @@ def test_a_filtered_target_never_reports_a_missing_target_event(fresh_engine):
assert _diagnostic_codes(engine, narrowed) == set()


def test_a_filtered_target_still_reports_person_mismatch(fresh_engine):
def test_a_filtered_target_still_reports_person_mismatch(fresh_cdm_engine):
"""A mismatch is observed on a row that is present, so it stays provable."""
engine = _seeded_engine(
fresh_engine,
fresh_cdm_engine,
conditions=[_condition(1, 10)],
measurements=[_modifier_of(100, 11, 1)],
)
Expand Down
Loading
Loading