Files
models/tests/io/test_storage.py

66 lines
2.8 KiB
Python

"""What this module covers: `models.io.storage`, reading a cohort build's file; and the rule that a model's folder
doesn't import the database layer, since the file is its only input.
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
"""
import ast
from datetime import date, datetime, timezone
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
import models
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortFileError
from models.io.storage import read_cohort
def _row(pac_id, fecha_indice, valor, fuente_id):
return {"pac_id": pac_id, "fecha_indice": fecha_indice, "fecha": fecha_indice,
"conocida_en": datetime(2025, 6, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda",
"codigo": "bethesda", "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical",
"fuente_id": fuente_id}
@pytest.fixture
def cohort_file(tmp_path):
"""Member 10 has two results; member 20 has one."""
rows = [_row(10, date(2025, 1, 1), "NORMAL", "a"), _row(10, date(2025, 1, 1), "NORMAL", "b"),
_row(20, date(2025, 2, 1), "LIEBG", "c")]
path = tmp_path / "1.parquet"
pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), path)
return path
def test_a_cohort_file_reads_as_a_frame(cohort_file):
"""Pins down: a build's file comes back with all its rows and columns. Fails if `read_cohort` drops rows or
columns, or refuses a file with the right schema."""
frame = read_cohort(cohort_file)
assert list(frame.columns) == SCHEMA.names
assert frame["pac_id"].tolist() == [10, 10, 20]
def test_a_file_with_other_columns_is_refused(tmp_path):
"""Pins down: `read_cohort` only accepts a cohort build's columns and types. Fails if it stops checking the
schema, which would let a model fail later on a missing column."""
path = tmp_path / "other.parquet"
pq.write_table(pa.table({"pac_id": [1]}), path)
with pytest.raises(CohortFileError, match="cohort build's columns"):
read_cohort(path)
def test_model_folders_do_not_import_the_database_layer():
"""Pins down: a model only sees frames: nothing under `models/cacu`, `cama` or `tea` imports `persistance` or
`core`. Fails when a model's folder imports either."""
package = Path(models.__file__).parent
offenders = []
for path in (file for domain in ("cacu", "cama", "tea") for file in (package / domain).rglob("*.py")):
for node in ast.walk(ast.parse(path.read_text())):
names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else \
[node.module or ""] if isinstance(node, ast.ImportFrom) else []
offenders += [(path.name, name) for name in names if name.split(".")[0] in ("persistance", "core")]
assert not offenders